Understanding the Bash Case Statement
Bash scripting is a powerful tool that allows you to automate tasks and write complex programs for the command line. One of the most important features of Bash scripting is the case statement, which simplifies complex conditionals with multiple choices. The case statement is similar to the switch statement in other programming languages, such as JavaScript or C. In this article, we will explore the Bash case statement and how to use it effectively in your scripts.
The keyword/keyphrase we will focus on in this article is [case statement bash].
Syntax of the Case Statement
The syntax of the Bash case statement is relatively simple. It uses multiple patterns separated by the |
operator and ends with the esac
keyword. The basic syntax is as follows:
case expression in
pattern1)
commands
;;
pattern2)
commands
;;
pattern3)
commands
;;
*)
commands
;;
esac
Here, expression
is the value that you want to match against the patterns. The in
keyword specifies the start of the pattern cases. Each pattern case must be enclosed in parentheses and followed by a list of commands to execute if the pattern matches. The body of each pattern case must end with ;;
to signify the end of the commands.
The final pattern case is denoted by the wildcard asterisk symbol *
, which matches any value that does not match the previous pattern cases. This is the default case that catches all other values.
Examples of Simple Case Statements
Let’s take a look at some simple examples of the Bash case statement. In the first example, we will use the case statement to perform different actions based on the user’s input.
#!/bin/bash
read -p "Enter your name: " name
case $name in
John)
echo "Hello, John!"
;;
Jane)
echo "Hi, Jane!"
;;
*)
echo "Nice to meet you, $name!"
;;
esac
In this example, we prompt the user to enter their name and then use the case statement to print a customized greeting based on their input. If the user enters “John”, the script will print “Hello, John!”. If the user enters “Jane”, the script will print “Hi, Jane!”. If the user enters any other value, the script will print “Nice to meet you, [name]!”.
In the next example, we will use the case statement to perform different actions based on the value of a variable.
#!/bin/bash
day=$(date +%A)
case $day in
Monday|Tuesday|Wednesday|Thursday|Friday)
echo "It's a weekday."
;;
Saturday|Sunday)
echo "It's the weekend!"
;;
esac
In this example, we use the date
command to get the current day of the week and store it in the day
variable. We then use the case statement to check whether the day is a weekday or the weekend and print a customized message accordingly.
These are just a few examples of the Bash case statement in action. In the next section, we will explore some more advanced techniques for using the case statement.
Advanced Techniques for Using the Bash Case Statement
In this section, we will explore some more advanced techniques for using the Bash case statement. These techniques will help you write more complex scripts and make your code more efficient and maintainable.
Using Multiple Pattern Cases
One of the most powerful features of the Bash case statement is the ability to use multiple pattern cases. This allows you to match against multiple values using the same set of commands. To use multiple pattern cases, simply separate the patterns with the |
operator. For example:
case $name in
John|Jane)
echo "Hello, $name!"
;;
*)
echo "Nice to meet you, $name!"
;;
esac
In this example, we match against both “John” and “Jane” and print a customized greeting for each. Any other value entered will trigger the default case.
Defining the Default Case
As we saw in the previous examples, the default case is used to catch any values that do not match the previous pattern cases. You can define the default case using the wildcard asterisk symbol *
. For example:
case $input in
1)
echo "Option 1 selected"
;;
2)
echo "Option 2 selected"
;;
*)
echo "Invalid input"
;;
esac
In this example, we check whether the user entered “1” or “2” and print a customized message for each. Any other value entered will trigger the default case and print “Invalid input”.
Using For Loops with the Case Statement
You can also use for loops with the Bash case statement to iterate over multiple expressions and execute the same set of commands for each. For example:
for name in John Jane Alice Bob
do
case $name in
John|Jane)
echo "Hello, $name!"
;;
*)
echo "Nice to meet you, $name!"
;;
esac
done
In this example, we use a for loop to iterate over the values “John”, “Jane”, “Alice”, and “Bob” and print a customized greeting for each. The case statement is used to match against “John” and “Jane”, while the default case is used for “Alice” and “Bob”.
Prompting the User for Input
You can also use the Bash case statement to prompt the user for input and execute different commands based on their response. For example:
read -p "Do you want to continue? [Y/n] " response
case $response in
[yY])
echo "Continuing..."
;;
[nN])
echo "Exiting..."
exit 1
;;
*)
echo "Invalid response"
exit 1
;;
esac
In this example, we prompt the user to enter “Y” or “N” and execute different commands based on their response. If the user enters “Y”, we print “Continuing…”. If the user enters “N”, we print “Exiting…” and exit the script with an error code of 1. If the user enters any other value, we print “Invalid response” and exit the script with an error code of 1.
Sending Signals to Processes
Finally, you can also use the Bash case statement to send signals to processes based on their status. For example:
case "$(pidof process-name)" in
"")
echo "Process not running"
;;
*)
echo "Process running, sending SIGTERM..."
kill -15 $(pidof process-name)
;;
esac
In this example, we check whether the process “process-name” is running using the pidof
command Linuxize. If the process is not running, we print “Process not running”. If the process is running, we send the SIGTERM
signal using the kill
command and print “Process running, sending SIGTERM…”. This will gracefully terminate the process without causing any data loss or corruption.
Bash Case Statement Best Practices
In this section, we will go over some best practices for using the Bash case statement. These practices will help you write cleaner, more efficient code that is easier to understand and maintain.
Use Meaningful Variable Names
When using the Bash case statement, it is important to use meaningful variable names that clearly describe what the variable represents. This will make your code more readable and easier to understand. For example:
case $weekday in
Mon|Tue|Wed|Thu|Fri)
echo "Weekday"
;;
Sat|Sun)
echo "Weekend"
;;
esac
In this example, we use the variable name weekday
to describe the value we are matching against. This makes it clear that we are checking whether the value is a weekday or a weekend.
Use Comments to Explain Your Code
Another best practice when using the Bash case statement is to use comments to explain your code. This will help others understand what your code is doing and why. For example:
# Check if the user is root
case "$USER" in
root)
echo "You are root"
;;
*)
echo "You are not root"
;;
esac
In this example, we use a comment to explain that we are checking whether the current user is root or not.
Use Indentation to Improve Readability
Indentation is another important aspect of writing clean, readable code. When using the Bash case statement, it is recommended to use indentation to make your code more readable. For example:
case $option in
1)
echo "Option 1 selected"
;;
2)
echo "Option 2 selected"
;;
*)
echo "Invalid option"
;;
esac
In this example, we use indentation to make it clear which commands are executed for each pattern case.
Use Lowercase for Variable Names
When using variables in Bash, it is recommended to use lowercase letters for variable names. This is a convention that is widely used and will make your code more consistent and easier to read. For example:
case $input in
y)
echo "Yes"
;;
n)
echo "No"
;;
*)
echo "Invalid input"
;;
esac
In this example, we use lowercase letters for the variable name input
.
Test Your Code
Finally, it is important to test your code thoroughly to ensure that it works as expected. This will help you catch any bugs or errors before your code is deployed to production. You can test your code by using different input values and verifying that the output is correct. For example:
# Test the case statement
assert_equals "$(bash my-script.sh John)" "Hello, John!"
assert_equals "$(bash my-script.sh Alice)" "Nice to meet you, Alice!"
In this example, we use a test framework to test our Bash script with different input values and verify that the output is correct. This will help us catch any errors or bugs before our code is deployed.
Bash Case Statement Examples
In this section, we will provide some Bash case statement examples to help you understand how the case statement works and how you can use it in your scripts.
Example 1: Simple Case Statement
The first example is a simple case statement that checks whether the user entered “Y” or “N” and prints a message based on their response:
read -p "Do you want to continue? [Y/n] " response
case $response in
[yY])
echo "Continuing..."
;;
[nN])
echo "Exiting..."
exit 1
;;
*)
echo "Invalid response"
exit 1
;;
esac
In this example, we use the read
command to prompt the user to enter “Y” or “N”. We then use a case statement to check whether the user entered “Y” or “N” and execute different commands based on their response. If the user enters “Y”, we print “Continuing…”. If the user enters “N”, we print “Exiting…” and exit the script with an error code of 1. If the user enters any other value, we print “Invalid response” and exit the script with an error code of 1.
Example 2: Case Statement with Multiple Pattern Cases
The second example is a case statement with multiple pattern cases that checks whether the input is a weekday or a weekend:
case $weekday in
Mon|Tue|Wed|Thu|Fri)
echo "Weekday"
;;
Sat|Sun)
echo "Weekend"
;;
esac
In this example, we use the variable name weekday
to describe the value we are matching against. We then use a case statement to check whether the value is a weekday or a weekend. If the value is a weekday (Monday to Friday), we print “Weekday”. If the value is a weekend (Saturday or Sunday), we print “Weekend”.
Example 3: Case Statement with Default Case
The third example is a case statement with a default case that checks whether the input is a valid option:
case $option in
1)
echo "Option 1 selected"
;;
2)
echo "Option 2 selected"
;;
*)
echo "Invalid option"
;;
esac
In this example, we use the variable name option
to describe the value we are matching against. We then use a case statement to check whether the value is a valid option. If the value is “1”, we print “Option 1 selected”. If the value is “2”, we print “Option 2 selected”. If the value is anything else, we print “Invalid option”.
Example 4: Case Statement with For Loop
The fourth example is a case statement with a for loop that prints a customized greeting for each name:
for name in John Jane Alice Bob
do
case $name in
John|Jane)
echo "Hello, $name!"
;;
*)
echo "Nice to meet you, $name!"
;;
esac
done
In this example, we use a for loop to iterate over the values “John”, “Jane”, “Alice”, and “Bob”. We then use a case statement to print a customized greeting for each name. If the name is “John” or “Jane”, we print “Hello, $name!”. If the name is anything else, we print “Nice to meet you, $name!”.
Conclusion
In this article, we have covered the basics of the Bash case statement and how it can be used to simplify complex conditionals with multiple choices. We have discussed some best practices for using the case statement, including using meaningful variable names, using comments to explain your code, using indentation to improve readability, using lowercase for variable names, and testing your code.
We have also provided some Bash case statement examples to help you understand how the case statement works and how you can use it in your scripts. These examples include a simple case statement that checks whether the user entered “Y” or “N”, a case statement with multiple pattern cases that checks whether the input is a weekday or a weekend, a case statement with a default case that checks whether the input is a valid option, and a case statement with a for loop that prints a customized greeting for each name.
By using the Bash case statement in your scripts, you can simplify complex conditionals and make your code more efficient and easier to understand. So go ahead and start using the Bash case statement in your scripts today!
Keep Learning and Growing
In this article, we have covered the basics of the Bash case statement and how it can be used to simplify complex conditionals with multiple choices. We have also discussed some best practices for using the case statement and provided some Bash case statement examples to help you understand how the case statement works and how you can use it in your scripts.
If you are interested in learning more about Bash scripting, be sure to check out our other great content. We have articles on a variety of topics, including command line basics, shell scripting, regular expressions, and more.
Remember, the more you learn and practice, the better you will become at Bash scripting. So keep learning and growing, and don’t be afraid to try new things. With the Bash case statement and other Bash scripting tools at your disposal, you can become a skilled and efficient Bash scripter in no time.
Thank you for reading, and happy scripting!
Answers To Common Questions
What is a case statement in Bash?
A case statement in Bash is a tool for simplifying complex conditionals with multiple choices.
How do you use a case statement in Bash?
To use a case statement in Bash, you define the variable to match, followed by the patterns to match against, and the commands to execute.
What are some best practices for using the case statement in Bash?
Some best practices for using the case statement in Bash include using meaningful variable names, using comments to explain your code, and testing your code thoroughly.
How does the case statement in Bash compare to if statements?
The case statement in Bash is more efficient than using multiple if statements, and it is easier to read and maintain.
What are some common use cases for the case statement in Bash?
Some common use cases for the case statement in Bash include prompting the user with yes or no, sending a signal to a process, and iterating over multiple expressions using a for loop.
What are some resources for learning more about the case statement in Bash?
Some resources for learning more about the case statement in Bash include online tutorials, Bash scripting books, and community forums such as Stack Overflow.