How to get a fall-through behavior in case statements in bash v3

bashcommand lineunix

I just tested the following syntax on Linux:

case "$OSTYPE" in linux-gnu*) ;;& linux*) echo $OSTYPE; ;; esac
case "$OSTYPE" in linux-gnu*) ;& linux*) echo $OSTYPE; ;; esac

which works without any problems (See: Can bash case statements cascade?) with GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu).

But on OSX I've the following errors:

-bash: syntax error near unexpected token `&'
-bash: syntax error near unexpected token `;'

It's GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13).

Any clues how to achieve the same fall-through behavior on bash v3?

Best Answer

Either upgrade your bash (homebrew) or you'll have to recode it using a series of if statements:

case "$OSTYPE" in linux-gnu*) ;;& linux*) echo $OSTYPE; ;; esac
case "$OSTYPE" in linux-gnu*) ;& linux*) echo $OSTYPE; ;; esac

would be

# first case
if [[ $OSTYPE == linux-gnu* ]]; then
    : # nothing in this branch
fi 
if [[ $OSTYPE == linux* ]]; then
    echo $OSTYPE
fi

# second case
function print_ostype { echo $OSTYPE; }
if [[ $OSTYPE == linux-gnu* ]]; then
    # nothing in this branch
    # include the next branch
    print_ostype
elif [[ $OSTYPE == linux* ]]; then
    print_ostype
fi

I used a function in the 2nd case to reduce code duplication, in case there's multiple statements.