1
option="${1}"
        case ${option} in
                1) do A
                   do B 
        ;;
                2) do A
                   do B
                   do C 
                ;;
        3) do A
           do B
           do C
        ;;
        esac

Above, I am repeating 'do C' for case 2 & 3. Instead of this redundancy, is there a way I can define a case that applies to all cases, except case 1 or a case which applies to case 2,3,5) (basically whichever case I want) like: allExceptCase1) OR Only2,3,5AndNotTheOthers)

codeforester
  • 39,467
  • 16
  • 112
  • 140
Shruti
  • 13
  • 4

2 Answers2

2

Here I've covered one case with two values and another "default" clause.

case ${option} in
  1) do A
     do B 
     ;;
  2|3) do A
       do B
       do C 
      ;;
   *) do D
      ;;
esac

RTFM: (http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html)

Stack: bash switch case matching multiple conditions

Community
  • 1
  • 1
Mort
  • 3,379
  • 1
  • 25
  • 40
2

Every option in a case statement is separate, but they are defined by shell patterns. Thus you could do this:

case ${option} in
  1) do A
     do B 
  ;;
  [23])
     do A
     do B
     do C 
  ;;
esac

You can nest case statements, too, so you could also do this:

case ${option} in
  [123])
    do A
    do B 
    case ${option} in
      [23]) do C 
      ;;
    esac
  ;;
esac

If you were willing to assume that ${option} would always be either 1, 2, or 3, then you could also do this:

do A
do B 
case ${option} in
  [23])
     do C 
  ;;
esac
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • Thank you! The nesting option is particularly helpful, because each of my cases have a few unique statements and a few common statements. – Shruti Apr 25 '16 at 20:45