0

I'm trying to get a case statement to match one of four inputs in a Bash/Zsh shell:

  1. v
  2. -v
  3. version
  4. --version

You can see where I'm going, right?

I'm looking for this in the below case statement:

case "$1" in
  ?(--)version|?(-)v)
    # do stuff
  ;;
esac

And I find that this isn't working. From what I've read, ?(pattern) is how to match 0 or one occurrences of a pattern.

I did have it working by matching the case

--version|version|-v|v)

But it would be nice to have something neater, plus, it's a learning experience!

I imagine this is probably down to me not escaping things properly, but I also tried encompassing my original string in double quotes ("), yet I got no output again.

Any advice?

  • 4
    Hi David, have you tried enabling extended globbing? Run that command shopt -s extglob before the case statement – monok Mar 11 at 17:41
  • 1
    While I applaud that you want to expand your knowledge, I just want to point out that readability is much more useful than niftyness. We could come up with a super short line. In time, however, it is likely that this line will become un-understandable mumbo-jumbo and totally impossible to debug. You will probably spend 1 hour understanding why and then move on by replacing it with your original clean line. Always use the KISS principle (Keep it Simple Stupid) – kvantour Mar 11 at 17:43
  • @monok Looks like that works! Although, that is an extra variance between the zsh and bash versions of the script I'm writing (I'm looking to keep them as close to identical as possible, for maintenance purposes!). I did find that (|--)version works! @kvantour, that's a reasonable comment, and I probably will take that approach. Thanks both! – David Allewell Mar 12 at 0:52
  • IMO, it doesn't make much sense to write a script compatible to run under bash and zsh. It will work only in rather simple cases, as these languages have a lot of differences. – user1934428 Mar 12 at 6:50
  • That's a fair comment, but so far in my use case the only difference I've run into is when sourcing RegEx matches after =~ (BASH_REMATCH vs match). – David Allewell Mar 12 at 23:40
0

To provide an answer to this, the best solution (if insisting on using some form of globbing) is:

(|--)version|(|-)v )

But as rightly pointed out by @kvantour, it's much better to just stick with the simpler:

--version|version|-v|v )

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.