Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fall through in a bash case statement in OSX?

Tags:

bash

macos

I have some bash scripts that I would like to run in OSX, but some of them contain the fallthrough case terminator ';&' which doesn't seem to work on Mac. Here's sample code:

#!/bin/bash
case $1 in
    test)
        echo "go" ;&    
    test)
        echo "go2" ;;
esac

In Cygwin, .\test.sh test produces

go
go2

but on OSX,

./test.sh: line 4: syntax error near unexpected token `&'
./test.sh: line 4: `            echo "go" ;&   
like image 949
tofutim Avatar asked Jan 30 '13 19:01

tofutim


People also ask

Does bash case fall through?

Since bash 4.0, a new operator ;& was introduced which provides fall through mechanism.

How do you write a case statement in bash?

The case statement starts with the case keyword followed by the $variable and the in keyword. The statement ends with the case keyword backwards - esac . The script compares the input $variable against the patterns in each clause until it finds a match.

What does Esac mean in shell script?

The basic syntax of the case... esac statement is to give an expression to evaluate and to execute several different statements based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.

Which command is used to close a case statement?

case Statement Syntax Each case statement starts with the case keyword, followed by the case expression and the in keyword. The statement ends with the esac keyword. You can use multiple patterns separated by the | operator. The ) operator terminates a pattern list.


2 Answers

Your code works as is on my ubuntu system, bash 4.2.24.

I think you are using an earlier version of bash which doesn't support ;& fall-through which was added since bash 4.

From wikipedia:

Fall through is done using ;& (new since Bash 4) whereas ;; acts as a case break.
like image 122
P.P Avatar answered Oct 19 '22 23:10

P.P


Perhaps you could try using /bin/zsh instead of /bin/bash? Your sample code works with “zsh 4.3.9” but not “bash 3.2.48” on my MacOS X 10.6.8.

Otherwise, the script has to be rewritten in some way… but it's hard to say exactly how without knowing what it does. Simply duplicating the code as needed is probably the simplest option and should work in every case.

like image 24
Magnus Gustavsson Avatar answered Oct 20 '22 00:10

Magnus Gustavsson