简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM