Situatie
Bash case statements are powerful yet easy to write. When you revisit an old Linux script you’ll be glad you used a case statement instead of a long if-then-else statement.
Solutie
Most programming languages have their version of a switch or case statement. These direct the flow of program execution according to the value of a variable. Typically, there is a branch of execution defined for each of the expected possible values of the variable and one catch-all or default branch for all other values. The logical functionality is similar to a long sequence of if-then statements with an else statement catching everything that hasn’t been previously handled by one of the if
statements.
The Generic case
The generic form of the case statement is this:
case expression in
pattern-1)
statement
;;
pattern-2)
statement
;;
.
.
.
pattern-N)
statement
;;
*)
statement
;;
esac
- A case statement must start with the case keyword and end with the
esac
keyword. - The expression is evaluated and compared with the patterns in each clause until a match is found.
- The statement or statements in the matching clause are executed.
- A double semicolon “
;;
” is used to terminate a clause. - If a pattern is matched and the statements in that clause executed, all other patterns are ignored.
- There is no limit to the number of clauses.
- An asterisk “
*
” denotes the default pattern. If an expression isn’t matched with any of the other patterns in the case statement the default clause is executed.
A Simple Example
This script tells us the opening hours for an imaginary shop. It uses the date
command with the +"%a"
format string to obtain the shortened day name. This is stored in the DayName
variable.
#!/bin/bash
DayName=$(date +"%a")
echo "Opening hours for $DayName"
case $DayName in
Mon)
echo "09:00 - 17:30"
;;
Tue)
echo "09:00 - 17:30"
;;
Wed)
echo "09:00 - 12:30"
;;
Thu)
echo "09:00 - 17:30"
;;
Fri)
echo "09:00 - 16:00"
;;
Sat)
echo "09:30 - 16:00"
;;
Sun)
echo "Closed all day"
;;
*)
;;
esac
Copy that text into an editor and save it as a file called “open.sh.”
We’ll need to use the chmod command to make it executable. You’ll need to do that for all of the scripts you create as you work through this article.
chmod +x open.sh
We can now run our script.
./open.sh
Leave A Comment?