Shruti Shruti - 7 months ago 19
Bash Question

How do I execute specific cases or exclude cases in a switch case statement (shell script)

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)

Answer

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