How do I write an IF statement with multiple conditions on the same line in Bash?
I'm writing a script right now in Bash that will execute two SQL queries and analyze that queried data. One of the command line inputs takes in an environment variable, which can be one of three values. If it's not one of those values, the script displays a message that prompts the user to enter in a correct value. However, the script doesn't properly check the value, instead prompting the user. Here is my code:
if [[ -z $ENV1 || $ENV1 != "ITF" || $ENV1 != "Prod" || $ENV1 != "QA" ]]
then
read -rp "Please ente开发者_如何转开发r the first environment (ITF, Prod, QA): " ENV1
fi
echo $ENV1
I think it's a problem with having multiple ||'s in the if line. How can I go about checking for all for of those conditions?
It looks to be a problem with your condition. Even if ENV1
is any of your options, one of the conditions will be true. For example, ENV1
could be "QA", but ENV1 != "Prod"
will still evaluate to true (0). Instead of ||
use &&
:
if [[ -z $ENV1 || ($ENV1 != "ITF" && $ENV1 != "Prod" && $ENV1 != "QA") ]]
then
read -rp "Please enter the first environment (ITF, Prod, QA): " ENV1
fi
echo $ENV1
Consider using case
instead, it will make the code clearer:
case $ENV1 in
"ITF" | "Prod" | "QA")
echo using $ENV1
;;
"")
read -rp "Please enter the first environment (ITF, Prod, QA): " ENV1
;;
*)
echo $ENV1 is not valid
read -rp "Please enter the first environment (ITF, Prod, QA): " ENV1
;;
esac
This is a good time to use select
:
select ENV1 in ITF Prod QA; do
case "$ENV1" in
ITF|Prod|QA) break;;
esac
done
Not so DRY though.
DRYer version
envs=( ITF Prod QA )
select ENV1 in "${envs[@]}"; do
for e in "${envs[@]}"; do
[[ $ENV1 == $e ]] && break 2
done
done
精彩评论