Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: if then statement for multiple conditions

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?

like image 410
Greg Avatar asked Mar 23 '26 12:03

Greg


2 Answers

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
like image 96
Adrian Frühwirth Avatar answered Mar 26 '26 05:03

Adrian Frühwirth


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
like image 29
konsolebox Avatar answered Mar 26 '26 06:03

konsolebox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!