How to use case statement in shell script

Question: I want to use switch/case statement (like in C/C++) in my shell script. Can you show me case examples written for a shell script?

In a shell script, the "case" statement is often useful when you want to change the control flow of a script based on the value of a variable or expression.

The following code snippets demonstrate the case syntax in a shell script. Note that the default case is preceded by "*)".

#!/bin/sh

CMD=$1

case "$CMD" in
        'start')
                echo "start"
                ;;
        'stop'|'halt')
                echo "stop or halt"
                ;;
        *)
                echo "Usage: ${0} [start|stop|halt]"
                ;;
esac

The case statement also supports pattern matching in evaluating each case branch. For example:

#!/bin/sh

case $filename in
        *.c )
                objname=${filename%.c}.o
                gcc $filename $objname
                ;;
        *.s )
                objname=${filename%.s}.o
                as $filename $objname 
                ;;
        *.o )
                ;;
        *)
                print "error: $filename is not a source or object file."
                ;;
esac

Subscribe to Ask Xmodulo

Do you want to receive Linux related questions & answers published at Ask Xmodulo? Enter your email address below, and we will deliver our Linux Q&A straight to your email box, for free. Delivery powered by Google Feedburner.

Leave a comment

Your email address will not be published. Required fields are marked *

Current day month ye@r *