Switch case with fallthrough?

Mischka picture Mischka · Apr 6, 2011 · Viewed 171k times · Source

I am looking for the correct syntax of the switch statement with fallthrough cases in Bash (ideally case-insensitive). In PHP I would program it like:

switch($c) {
    case 1:
        do_this();
        break;
     case 2:
     case 3:
        do_what_you_are_supposed_to_do();
        break;
     default:
        do_nothing(); 
}

I want the same in Bash:

case "$C" in
    "1")
        do_this()
        ;;
    "2")
    "3")
        do_what_you_are_supposed_to_do()
        ;;
    *)
        do_nothing();
        ;; 
esac

This somehow doesn't work: function do_what_you_are_supposed_to_do() should be fired when $C is 2 OR 3.

Answer

geekosaur picture geekosaur · Apr 6, 2011

Use a vertical bar (|) for "or".

case "$C" in
"1")
    do_this()
    ;;
"2" | "3")
    do_what_you_are_supposed_to_do()
    ;;
*)
    do_nothing()
    ;;
esac