How to use Case statement in shell scripting
How to use Case statements in shell scripting?
In this article, we will learn how to use Case statements in shell scripting with a basic example.
The case...esac Statement
You can use multiple if...elif statements to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.
Unix Shell supports case...esac statement which handles exactly this situation, and it does so more efficiently than repeated if...elif statements.
There is only one form of case...esac statement which has been described in detail here −
case...esac statement
The case...esac statement in the Unix shell is very similar to the switch...case statement we have in other programming languages like C or C++ and PERL, etc.
#! /bin/bash
#case statement
vehicle=$1
case $vehicle in
"car" )
echo "Rent of $vehicle is 100 dollar" ;;
"van" )
echo "Rent of $vehicle is 80 dollar" ;;
"truck" )
echo "Rent of $vehicle is 90 dollar" ;;
*)
echo "unknown vehicle"
esac
Example:
echo -e "Enter your name \c"
read vehicle
case $vehicle in
"car" )
echo "Rent of $vehicle is 100 dollar" ;;
"van" )
echo "Rent of $vehicle is 80 dollar" ;;
"truck" )
echo "Rent of $vehicle is 90 dollar" ;;
*)
echo "unknown vehicle"
esac
0 comments
Please leave your comments...... Thanks