I want to check input parameters in my Bash script. There can be a lot of combinations, so I decided to use a construction like this:
if ( [[ "$2" = "(PARAM1|PARAM2|PARAM3)" && "$3" = "(PARAM11|PARAM22|PARAM33)" ]] )
I expected that this line will check which parameter is specified (there can be input combinations like PARAM1 PARAM22 or PARAM11 PARAM3, etc.).
But it doesn't work. Should I use arrays or just need to try another syntaxes?
You might want to re-read the bash man page's sections on "Compound commands" and "CONDITIONAL EXPRESSIONS" (caps per the man page). Your question puts the condition inside a subshell, which is unnecessary.,
If you want to match arguments ($2, $3, etc) against regular expressions, you can use a format like this:
if [[ $2 =~ ^(foo|bar)$ ]]; then
...
fi
Or:
if [[ $2 =~ ^(foo|bar)$ ]] && [[ $3 =~ ^(baz|flarn)$ ]]; then
...
fi
That said, a regular expression isn't really needed here. A regex uses more CPU than a simple pattern match. I might handle this using case statements:
case "$2" in
foo|bar)
case "$3" in
glurb|splat)
# do something
;;
esac
;;
baz)
# do something else
;;
esac
The exact way you handle parameters depends on what you actually need to do with them, which you haven't shared in your question. If you update your question to include more detail, I'd be happy to update this answer. :)
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