arcol February 2016

Unlimited choices in BASH case statement

Consider this simple bash snippet:

case $OPTION in
  1)
    IMAGE=${options[0]%.tar}
    ;;
  2)
    IMAGE=${options[1]%.tar}
    ;;
  3)
    IMAGE=${options[2]%.tar}
    ;;
  4)
    IMAGE=${options[3]%.tar}
    ;;
  *)
    echo "invalid option"
    exit 1
esac

In my real script the numbers goes up to 30. Which makes it pretty long. Can I somehow specify cases with a variable?

Something like this:

case $OPTION in
  $i)
    IMAGE=${options[$(($i-1))]%.tar}

Any pointer is much appreciated.

Answers


umläute February 2016

you can match against multiple patterns in a single clause:

case $OPTION in
    1|2|3:
       echo "$OPTION is one, two or three"
       ;;
esac

if this is still too much typing for you, you can use some simple pattern matching:

case $OPTION in
  # the following matches
  #  - single-digit numbers 0-9
  #  - two-digit numbers starting with either 1 or 2
  #  - the number 30
  [0-9]|[12][0-9]|30)
     IMAGE=${options[$(($OPTION-1))]%.tar}
     ;;
  *)
     echo "invalid option" 1>&2
     exit 1
esac


glenn jackman February 2016

Oh my, DRY:

if (( 1 <= OPTION && OPTION <= 30 )); then
    IMAGE=${options[OPTION-1]%.tar}
else
    echo "invalid option" >&2
    exit 1
fi

Post Status

Asked in February 2016
Viewed 3,248 times
Voted 9
Answered 2 times

Search




Leave an answer