Bash Case Statement with Examples

Table of Contents
Bash Case Statement with Examples
Bash case statements mainly used to replace multi-level if… else statement. You can use the case statement to match one variable against several values. The bash case statement is similar to switch statement in C programming but bash switch statement does not go ahead one it’s found. The Bash case statement is more readable so anyone can understand it easily. In this tutorial, you are going to learn how to use Bash case statement with examples in shell programming.
Basic Syntax
Following is the basic syntax for bash case statement in shell programming:
case $VARIABLE_NAME in PATTERN_1) COMMAND_1 ..... COMMAND_N ;; PATTERN_2) COMMAND_1 ..... COMMAND_N ;; PATTERN_N) COMMAND_1 ..... COMMAND_N ;; *) COMMAND_1 .... COMMAND_N ;; esac
-
- The case statement always starts with
case
keyword and ends withesac
keyword. - The Pattern ends with
)
and you can use wildcard patterns separated by|
operator. like give below
- The case statement always starts with
PATTERN_1|PATTERN_2|PATTERN_3) COMMAND_1 .... COMMAND_N ;;
-
- Pattern with commands is called
clause
each clause ends with;;
. *
can be used for the default case.
- Pattern with commands is called
Bash Case Statement Example
The following example is based on one bash case statement. It will ask you to enter Linux distro name and tell you either it is based on Debian or not.
#!/bin/bash echo -n "Enter the Linux distro name: " read DISTRO case $DISTRO in Ubuntu) echo -n "Yes, it is based on Debian." ;; "Linux Mint" | "Elementory OS") echo -n "Yes, it is based on Debian." ;; CentOS | Fedora | RHEL) echo -n "No, its not based on Debian" ;; *) echo -n "Can find distro information" ;; esac
Copy-paste above code in the file named distros.sh and run it like given below:
bash distros.sh
The output should be:
$ bash distros.sh Enter the Linux distro name: Ubuntu Yes, it is based on Debian. $ bash distros.sh Enter the Linux distro name: CentOS No, its based on Debian. $ bash distros.sh Enter the Linux distro name: Linux Mint Yes, it is based on Debian. $ bash distros.sh Enter the Linux distro name: solus Can find distro information
Conclusion
Here you have successfully learned how to use Bash Case Statement with Examples. If you have any queries please don’t forget to comment below.
LATEST POSTS
-
How to Install Android Studio in Linux
-
How to Use Linux Screen Command With Examples
-
How to Install Apache on Debian 9
-
Secure Nginx with Let’s Encrypt SSL on CentOS 7
-
How to Check if Ports are Open in Linux
-
How to Install and Use Docker on Ubuntu 18.04
-
How to install Dropbox on Debian 9 Server and Desktop
-
How to Install Python on Linux Mint 19
-
How to Set Up Cron Job on CentOS 7
-
How to install Laravel PHP Framework With Nginx on Ubuntu 18.04
-
How to Install Google Chrome on Linux Mint 19
-
How to Install Postman on Debian 9