How To Use Case Statements on Bash Script in Oracle Linux 9.4
To Use Case Statements On Bash Script In Oracle Linux 9.4
Introduction:
The fundamental syntax of the case...esac statement involves providing an expression to evaluate and executing various statements based on the value of that expression. The interpreter assesses each case in relation to the expression's value until a match is identified. If no matches are found, a default condition will be applied.
Procedure:
Step 1: Check the OS version
[root@localhost ~]# cat /etc/os-release
NAME="Oracle Linux Server"
VERSION="9.4"
ID="ol"
ID_LIKE="fedora"
VARIANT="Server"
VARIANT_ID="server"
VERSION_ID="9.4"
PLATFORM_ID="platform:el9"
PRETTY_NAME="Oracle Linux Server 9.4"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:oracle:linux:9:4:server"
HOME_URL="https://linux.oracle.com/"
BUG_REPORT_URL="https://github.com/oracle/oracle-linux"
ORACLE_BUGZILLA_PRODUCT="Oracle Linux 9"
ORACLE_BUGZILLA_PRODUCT_VERSION=9.4
ORACLE_SUPPORT_PRODUCT="Oracle Linux"
ORACLE_SUPPORT_PRODUCT_VERSION=9.4
Step 2: Create the script file
[root@localhost ~]# vi case_script_1
#!/bin/bash
echo "Which color do you like best?"
echo "1 - Blue"
echo "2 - Red"
echo "3 - Yellow"
read color;
case $color in
1) echo "Blue is a primary color.";;
2) echo "Red is a primary color.";;
3) echo "Yellow is a primary color.";;
*) echo "This color is not available. Please choose a different one.";;
esac
Step 3: Change the permissions by using following command
[root@localhost ~]# chmod +x case_script_1
Step 4: Run the script by using following command
[root@localhost ~]# ./case_script_1
Which color do you like?
1 - Blue
2 - Red
3 - Yellow
1
Blue is a primary color
[root@localhost ~]# ./case_script_1
Which color do you like?
1 - Blue
2 - Red
3 - Yellow
2
Red is a primary color
[root@localhost ~]# ./case_script_1
Which color do you like?
1 - Blue
2 - Red
3 - Yellow
3
Yellow is a Primary color
[root@localhost ~]# ./case_script_1
Which color do you like?
1 - Blue
2 - Red
3 - Yellow
4
This color is not valid, select another one
Step 5:Create the another script
[root@localhost ~]# vi case_script_2
read fruit
case $fruit in
"banana" | "papaya" | "mango")
echo "It's a tropical fruit!"
;;
*)
echo "It's not a tropical fruit"
;;
esac
Step 6: Change the permissions by using following command
[root@localhost ~]# chmod +x case_script_2
Step 7: Run the script file by using following command
[root@localhost ~]# ./case_script_2
Enter any fruit name?
banana
is's a tropical fruit!
[root@localhost ~]# ./case_script_2
Enter any fruit name?
Papaya
is's a tropical fruit!
[root@localhost ~]# ./case_script_2
Enter any fruit name?
graphes
is's not a tropical fruit
Conclusion:
We have reached the end of this article. In this guide, we have walked you through the steps required to use Case Statements on Bash Script in Oracle Linux 9.4 Your feedback is much welcome.