Case statement in bash scripts

Discussion in 'General Linux' started by Mark Harris, Mar 1, 2014.

  1. Mark Harris

    Mark Harris New Member

    Messages:
    12
    Likes Received:
    6
    Trophy Points:
    3
    I have now a general understanding of how the case statement works, but I'm wondering if there is a special meaning in the punctuation, I guess we would call it, in the following example from Pro Bash Programming:

    case $1 in
    *[!0-9]*) false;;
    *) true ;;
    esac

    I get that the latter *) (before true) means the default, but is there a special meaning to surrounding [!0-9] (not a digit) with asterisks?

  2. MikeyD

    MikeyD Active Member

    Messages:
    232
    Likes Received:
    111
    Trophy Points:
    43
    Yes, it is a regular expression grabbing anything NOT a digit regardless of what comes before and after it. So really it's just part of the conditional parameter. Any regular expression can be used as a condition in a bash case statement.

    For example:
    *[0-9][0-9] would pick up "mikeyd99" but it wouldn't pick up "mikey99d" because there are additional characters before and after the expression, but the one asterisk says "give me any word that ends in two digits ([0-9][0-9])" whereas *[0-9][0-9]* says "give me any word that contains two digits back-to-back regardless of what comes before or after" this expression would pick up "mikey99d"

    I'm not a great explainer, here is a good tutorial with some examples of using wildcards "*" and "?" if you need more clarity:
    http://tldp.org/LDP/abs/html/globbingref.html
  3. Mark Harris

    Mark Harris New Member

    Messages:
    12
    Likes Received:
    6
    Trophy Points:
    3
    Thanks. That meaning should have been obvious, I guess I was looking for something more arcane:)
  4. MikeyD

    MikeyD Active Member

    Messages:
    232
    Likes Received:
    111
    Trophy Points:
    43
    Yeah even coming from other programming languages, shell case statements look odd with no "break" statements and the use of ")".
    Just any type of reg exp can be used for matching before the ")" (I still prefer the traditional colon though)

Share This Page