Команди Linux

BASH Case Command

BASH Case Command

Bash case command is used to take proper action by comparing data like if statement. It works like a switch-case statement of other standard programming languages. This command starts with 'case' statement and closes by 'esac' statement. No break statement is used in the case command and double bracket (;;) is required to mention the statement(s) for any particular matching. This command expands the expression and tries to match with the given pattern and the exit status code of this command will be zero if no matching will be found. Some common examples of case statements are shown in this tutorial.

Example-1: simple case statement

A single conditional expression is used in bash case command to generate the output based on the matching condition. Create a bash file named case1.sh with the following bash script. The script will take a string value and match the value with each expression. The following script will generate “No Entry Found” if no matching expression exists,
case1.sh

#!/bin/bash
echo "Type your name"
read name
case $name in
Yesmin)
echo "Your favorite color is blue" ;;
Fahmida)
echo "Your favorite drink is Sprite" ;;
*)
echo "No Entry Found" ;;
esac

Run the script.

$ bash case1.sh

Output:

The file is executed with a valid and invalid input here to test the output.

Example-2: multiple case statement with pipe

Multiple case expressions can be applied in the bash script to execute different types of statements. Pipe ( | ) symbol can be used to assign the multiple expressions. Create a bash file named case2.sh with the following script. After running the script, if the input value matches with any expression then the corresponding text value will be printed.
case2.sh

#!/bin/bash
echo "Type your ID number"
read ID
case $ID in
65341)
echo "Your position is 1st" ;;
97564|88453)
echo "Your position is 2nd" ;;
45087)
echo "Your position is 3rd" ;;
*)
echo "Invalid ID" ;;
esac

Run the script .

$ bash case2.sh

Output:

This script also works like the previous example. The only difference is that the multiple expression values are tested for a single output.

Example-3: How to quit from case/esac statement block

When the bash case command is used under an infinite loop the exit command is required to use to terminate the loop. This example shows how these types of the task can be done. Create a text file named case3.sh with the following script. This script will take any number from 1 to 3 as input. If the input is 1 then two numbers will be added, if the input is 2 then two numbers will be subtracted and if the input number is 3 then two numbers will be multiplied. The output will be “Invalid entry” if the input number is more than 3 or less than 1 or empty.
case3.sh

#!/bin/bash
#!/bin/bash
while(true)
do
a=8
b=4
((x=$a+$b))
((y=$a-$b))
((z=$a*$b))
echo "Type 1 or 2 or 3"
read ans
case $ans in
1) echo "The sum of $a and $b is $x & exit" ;;
2) echo "The subtraction of $a and $b is $y & exit" ;;
3) echo "The multiplication of $a and $b is $z & exit" ;;
*) echo "Invalid entry"
esac
done

Run the script.

$ bash case3.sh

Output:

The script will continue to execute until ctrl+c will be pressed.

Example-4: Checking empty command line argument value

Command line argument variable can be used in the bash case statement. Create a file named case4.sh with the following script that will check the value of the second argument variable.

#!/bin/bash
case "$2" in
"Ubuntu")
echo "The second argument is $2."
;;
"CentOS")
echo "The second argument is $2."
;;
"")
echo "The second argument is empty."
;;
esac

Run the script.

$ bash case4.sh

Output:

Here, the script is executed without any second command line argument value for the first time and the output shows “The second argument is empty”. When the script is executed with a second command line argument value for the second time then no output is shown.

Example-5: multiple case statement based on user input

Create a bash file named case5.sh with the following script. The script will take month name as user input. If the month name match with any case value then a particular text message will be assigned into the variable Message. Input value must be the full month name or three characters month name.

case5.sh

#!/bin/bash
echo "Type the name of a month"
read month
case $month in
January|Jan*)
Message=" 21st February is our International Mother's day."
;;
February|Feb*)
Message=" 21st February is our International Mother's day."
;;
March|Mar*)
Message="9th March is the world kidney day."
;;
April|Apr*)
Message="The current month is not February"
;;
May|May*)
Message="The current month is February"
;;
June|Jun*)
Message="The current month is February"
;;
*)
Message="No matching information found"
;;
esac
echo $Message

Run the script.

$ bash case5.sh

Output:

The following output will appear for the input value, 'March' or 'Mar'.

Example-6: Check variable in the bash case statement

Any string value can be printed by checking the value of the command line argument variable. Create a text file named case6.sh with the following script. In this example, the value of the first argument variable is checked and if the value is empty then a string, “I like bash programming” will be printed.

case6.sh

#!/bin/bash
case $1 in
("") echo "I like bash programming";
esac

Run the script.

$ bash case6.sh

Output:

This script is executed with and without first arguments. There will be no output if no command line argument variable passes.

Conclusion

Different uses of bash case command are shown in this article. If the readers practice these examples properly then it will be easier for them to solve many bash programming problems.

5 найкращих аркадних ігор для Linux
В наш час комп’ютери - це серйозні машини, що використовуються для ігор. Якщо ви не можете отримати новий високий бал, ви зрозумієте, що я маю на уваз...
Битва за Веснот 1.13.6 Розробка випущена
Битва за Веснот 1.13.6, випущений минулого місяця, є шостим випуском розробки в 1.13.x, і це забезпечує низку вдосконалень, особливо до інтерфейсу кор...
Як встановити League of Legends на Ubuntu 14.04
Якщо ви шанувальник League of Legends, то це можливість для вас тестувати League of Legends. Зверніть увагу, що LOL підтримується на PlayOnLinux, якщо...