Notes

CASE Statement

Edit on GitHub


Bash Scripting
2 minutes

CASE statements are similir to ELIF statements, use case if elif statements are more than 3.

1case expression in
2  pattern1 )
3    statements ;;
4  pattern2 ) 
5    statements 
6    ;;
7esac

Exactly how you use fi to end if statements, you close a case statement with esac (which is the alphabetic opposite of case, case spelled backwards).

;; marks the end of a statement.

Example:

 1echo -n "give me a domain: "
 2read domain
 3
 4case $domain in
 5  "google.com" )
 6    echo "Google, wow!" ;;
 7  "twitter.com" )
 8    echo "Twitter -_-" ;;
 9  "udemy.com" ) 
10    echo "Udemy, YES!" ;;
11  "aamnah.com" )
12    echo "Aamnah.com, brilliant. Let's PING!"
13    ping -c3 aamnah.com ;;
14esac

1case "$1" in
2  start) 
3    /usr/sbin/sshd
4    ;;
5  stop)
6    kill $(cat /var/run/sshd.pid)
7    ;;
8esac

In the example above if $1 is equal to start then /usr/sbin/sshd is executed. If $1 is equal to stop then the kill command is executed. If $1 matches neither start nor stop then nothing happens and the script continues after the statement.

Note: case statements (start and stop in the example above) are case-sensitive.

 1case "$1" in
 2  start) 
 3    /usr/sbin/sshd
 4    ;;
 5  stop)
 6    kill $(cat /var/run/sshd.pid)
 7    ;;
 8  *)
 9    echo "Usage start|stop" 
10    exit 1
11    ;;
12esac

In this example, anything other than start or stop will show usage instructions.

wildcards *

1*)
2  echo "Usage start|stop" 
3  exit 1
4  ;;

is the same as

1*)
2  echo "Usage start|stop" ; exit 1
3  ;;

check multiple conditions |

You can use pipe | to seperate multiple case statement conditions/options. | servers as OR

 1case "$1" in
 2  start|START) 
 3    /usr/sbin/sshd
 4    ;;
 5  stop|STOP)
 6    kill $(cat /var/run/sshd.pid)
 7    ;;
 8  *)
 9    echo "Usage start|stop" 
10    exit 1
11    ;;
12esac

Character classes []

Character classes are simply a list of characters between brackets []. Like so:

1[yY][nN]

A character class matches exactly one character, and a match occurs for any of the including characters in the brackets.

1[yY][eE][sS]

will check for all case-sensitive possibilities of yes. yes, Yes, yEs, yeS, YEs, yES, YeS, and so on.. Here’s a code example:

 1read -p "Enter y or n: " ANSWER
 2
 3case "$ANSWER" in
 4  [yY]|[yY][eE][sS] )
 5    echo "You answered yes." ;;
 6  [nN]|[nN][oO] )
 7    echo "You answered no." ;;
 8  * )
 9    echo "Invalid answer." ;;
10esac