Assume there are three valid values for a Bash variable $x
: foo
, bar
, and baz
. How does one write an expression to determine whether $x
is one of these values? In Python, for example, one might write:
x in ('foo', 'bar', 'baz')
Is there a Bash equivalent, or is it necessary to perform three comparisons? Again, in Python, one could write:
x == 'foo' or x == 'bar' or x == 'baz'
What's the correct way to express the above in Bash?
Simplest way:
case $x in
foo|bar|baz) echo is valid ;;
*) echo not valid ;;
esac
A bit more complicated
shopt -s extglob
if [[ $x == @(foo|bar|baz) ]]; then
echo is valid
else
echo not valid
fi
More complicated:
is_valid() {
local valid=( foo bar baz )
local value=$1
for elem in "${valid[@]}"; do
[[ $value == $elem ]] && return 0
done
return 1
}
if is_valid "$x"; then
echo is valid
else
echo not valid
fi
Use a case statement:
var=bar
case $var in
foo | bar | baz )
echo "Matches"
;;
esac
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With