Linux Shell Script Conditional Statements-case…esac

If we need to check multiple conditions, we can use case…esac statement. It’s handy when we create a menu with many items.

Syntax for the case…esac statement:

case value in
    pattern)
        command;;
    pattern2)
        command;;
    pattern3)
        command;;
    *) 
        defauld command if nothing matches;;
esac

Example, find the today’s day:

#!/bin/bash
NOW=$(date -d "$1" +"%a")
case $NOW in
    Mon)
        echo "Mon";;
    Tue)
        echo "Tue";;
    Wed)
        echo "Wed";;
    Thu)
        echo "Thu";;
    Fri)
        echo "Fri";;
    Sun)
        echo "Sun";;
    *) 
	echo "Sat";;
esac

Another example:

#!/bin/bash
COMMAND="d"
case $COMMAND in
    "d")
        echo "Perform daily work";;
    "w")
        echo "Perform weekly work";;
    *)
        echo "Perform monthly work";;		
esac

Save the code as case_esac.sh and run as:

$ bash case_esac.sh

Output:

Perform daily work

See our all the courses and lessons. Do not forget to explore code examples in our GitHub repository.

Follow us on social media
Follow Author