4

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?

1
  • 3
    you forked a subshell for nothing and you should use regular expression match here =~. Commented Mar 17, 2015 at 15:00

1 Answer 1

7

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. :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for your help, I've tried to use case in my script and it works ok :)
That's great, I'm glad I could help. Please feel free to click the checkmark beside my answer in order to close the question.

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.