Reputation: 257
I am writing a bash script to setup different types of restores. I am setting up an "if" statement to compare multiple variables.
restore=$1
if [ "$restore" != "--file" ] || [ "$restore" != "--vhd"] || [ "$restore" != "--vm" ]
then
echo "Invalid restore type entered"
exit 1
fi
What I am looking for is to see if there is an easier way to put all of those conditions in one set of brackets like in Python. In Python I can run it like this:
import sys
restore = sys.argv[1]
if restore not in ("--file", "--vhd", "--vm"):
sys.exit("Invalid restore type entered")
So basically, is there a bash alternative?
Upvotes: 2
Views: 3645
Reputation: 45706
Use a switch for a portable (POSIX) solution:
case ${restore} in
--file|--vhd|--vm)
;;
*)
echo "Invalid restore type entered"
exit 1
;;
esac
or even
case ${restore#--} in
file|vhd|vm)
;;
*)
echo "Invalid restore type entered"
exit 1
;;
esac
Upvotes: 8
Reputation: 75608
Use extended patterns:
shopt -s extglob
restore=$1
if [[ $restore != @(--file|--vhd|--vm) ]]
then
echo "Invalid restore type entered"
exit 1
fi
Or use regex:
restore=$1
if [[ ! $restore =~ ^(--file|--vhd|--vm)$ ]]
then
echo "Invalid restore type entered"
exit 1
fi
Upvotes: 4