Saturday 15 June 2013

shell - Checking a bash variable against multiple values -


I want to check the input parameters in my Bash script. There may be a lot of combinations, so I decided to use a construction like this:

  if ([["$ 2" = "(PARAM1 | PARAM2 | PARAM3)" & amp; ; I was hoping this line will determine which parameter is specified (input combinations like  PARAM1 PARAM22   

/ code> or PARAM11 PARAM3 < / Code>, etc.).

But this does not work. Should I use an array or just try some other syntax?

< Div class = "post-text" item Prop = "text">

You want to re-read Bash, the section "Compound command" on the man page and section on "conditional expansions" (man page per cap). Your question places the condition inside a subsealand, which Unnecessary.

If you want to match the arguments ( $ 2 , $ 3 , etc.) regularly, expression, You can use:

  if [[$ 2 = ~ ^ (foo | times) $]] then ... fi  

or :

  if [[$ 2 = ~ ^ (foo | Bar) $]] & amp; Amp; [[$ 3 = ~ ^ (falcon | flirt) $]]; Then ... fi  

He said, a regular expression is not really needed here, using a more CPU than a Rijks simple pattern match is. I can handle it by using the case statements:

  case "$ 2" in "foo" bar) "$ 3" glurb; Splat) # do something; ASAC ;; Falcon) # Something else ;; ASAC  

handle the parameters correctly, depending on what you really need to do, which you have not shared in your question. If you update your question to include more details, then I will be happy to update this reply. :)


No comments:

Post a Comment