The following article describes the basic syntax and includes a simple example of the BASH CASE statement usage.
The CASE statement is the simplest form of the IF-THEN-ELSE statement in BASH.
You may use the CASE statement if you need the IF-THEN-ELSE statement with many ELIF elements.
With the BASH CASE statement you take some value once and then test it multiple times.
Basic Syntax of the CASE Statement
case $variable in
pattern-1)
commands
;;
pattern-2)
commands
;;
pattern-3|pattern-4|pattern-5)
commands
;;
pattern-N)
commands
;;
*)
commands
;;
esac
Example of a BASH Script with the CASE Statement
#!/bin/bash
printf 'Which Linux distribution do you know? '
read DISTR
case $DISTR in
ubuntu)
echo "I know it! It is an operating system based on Debian."
;;
centos|rhel)
echo "Hey! It is my favorite Server OS!"
;;
windows)
echo "Very funny..."
;;
*)
echo "Hmm, seems i've never used it."
;;
esac
Run the script as follows:
$ ./testcase.sh Which Linux distribution do you know? centos Hey! It is my favorite Server OS! $ ./testcase.sh Which Linux distribution do you know? rhel Hey! It is my favorite Server OS! $ ./testcase.sh Which Linux distribution do you know? ubuntu I know it too! It is an operating system based on Debian. $ ./testcase.sh Which Linux distribution do you know? pfff Hmm, seems i've never used it.