Bash Case Statement with Examples

Bash Case Statement With Examples
Bash Case Statement With Examples

Bash Case Statement with Examples

Bash case statements can be 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 with esac keyword.
    • The Pattern ends with ) and you can use wildcard patterns separated by | operator. like give below
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.

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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here