How to use case statement in shell script

Last updated on July 24, 2020 by Dan Nanni

Question: I want to use switch/case statement (like in C/C++) in my bash 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 an expression.

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

#!/bin/bash

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/bash

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

If you find this tutorial helpful, I recommend you check out the series of bash shell scripting tutorials provided by Xmodulo.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean