Working with CASE Switches in Bash Shell Scripting

Channel: Linux
Abstract: echo "Input is a characterservice myservice {start|stop|restart|status}"

In Bash Shell Programming case is very useful for replacing a large elif (Else IF) ladder. For example in any situation where we are using multiple if..elif statements, that can be easily replace with case…esac statements

In bash shell case statements are started with keyword case and ends with esac.

  case $VARIABLE  in
	pattern1)
		<program code here>
		;;
	pattern2)
		<program code here>
	    ;;
	pattern10)
		<program code here>
		;;
	*)
		<program code here>
	    ;;
  esac
 

In above syntax $VARIABLE will be the value which will be matched with patterns and the of matching pattern code block will be executed. All the program code must be ended with ;;.

Please find few examples below to use case…esac statements.

1. Check Input Number

This is very simple and meaningful example of case statement. In this example script will take a input of single character and print cosponsoring English word. If you input any non digit character or multiple digits it will show 「Not a single numeric character!」.

#!/bin/sh

read -p "Enter a numeric Character [0-9] " NUMBER

case $NUMBER in
        0) echo "Zero";;
	1) echo "One" ;;
	2) echo "Two" ;;
	3) echo "Three" ;;
	4) echo "Four" ;;
	5) echo "Five" ;;
	6) echo "Six" ;;
	7) echo "Seven" ;;
	8) echo "Eight" ;;
	9) echo "Nine" ;;
	*) echo "Not a single numeric character!" ;;
esac
2. Using WildCard Character in pattern

Case statements also allowed to use wildcard characters in pattern like – (defining range), * (match anything), | ( define multiple patterns ) etc.

#!/bin/sh

read -p "Enter any alphanumeric character :" CHAR

case $CHAR in
    [0-9]*)
        echo "Input is a digit!"
        ;;

    [a-z]*|[A-Z]*)
        echo "Input is a character!"
        ;;

    *)
        echo "Input is a non alphanumeric character"
        ;;
esac
3. Uses in Init Scripts

If you have ever edited any of init scripts, you must be seen that most of init scripts uses case statements for running commands like start, stop etc.

case "$1" in
        start)
            start
            ;;

        stop)
            stop
            ;;

        status)
            status myservice
            ;;

        restart)
            stop
            start
            ;;

        *)
            echo "Use command: service myservice {start|stop|restart|status}"
            exit 1
esac

Thanks for reading this port.. We will add more examples here soon.

Ref From: tecadmin

Related articles