I'm trying to write a Bash script that uses a variable as a pattern in a case statement. However, I just cannot get it to work.
Case statement:
case "$1" in $test) echo "matched" ;; *) echo "didn't match" ;; esac
I've tried this with assigning $test
as aaa|bbb|ccc
, (aaa|bbb|ccc)
, [aaa,bbb,ccc]
and several other combinations. I also tried these as the pattern in the case statement: @($test)
, @($(echo $test))
, $($test)
. Also no success.
For clarity, I would like the variable to represent multiple patterns like this:
case "$1" in aaa|bbb|ccc) echo "matched" ;; *) echo "didn't match" ;; esac
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
The case statement starts with the case keyword followed by the $variable and the in keyword. The statement ends with the case keyword backwards - esac . The script compares the input $variable against the patterns in each clause until it finds a match.
esac statement is to give an expression to evaluate and to execute several different statements based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.
There is no difference if you do not put $* or $@ in quotes. But if you put them inside quotes (which you should, as a general good practice), then $@ will pass your parameters as separate parameters, whereas $* will just pass all params as a single parameter.
You can use the extglob
option:
#! /bin/bash shopt -s extglob # enables pattern lists like +(...|...) test='+(aaa|bbb|ccc)' for x in aaa bbb ccc ddd ; do echo -n "$x " case "$x" in $test) echo Matches. ;; *) echo Does not match. esac done
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