Shruti
Shruti

Reputation: 13

How do I exclude certain cases in a switch case statement?

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)

Upvotes: 1

Views: 1094

Answers (2)

John Bollinger
John Bollinger

Reputation: 180968

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

Upvotes: 2

Mort
Mort

Reputation: 3549

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

Upvotes: 2

Related Questions