2

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?

0

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

konsolebox, that worked great. Thank you for the insight. I will make sure to accept your answer when it allows me to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.