I have a couple of arguments inside a list (array, e.g. $@) and I'd like to know if the option -v is in the list.

In Python I would simply do:

verbose = "-v" in sys.argv

How do I achieve that in shell without much code?

  • Imho, the best way to do argument parsing in shell scripts is with getopt. See man getopt. – HalosGhost Jul 17 '14 at 23:40
  • 1
    @HalosGhost getopts is easier to use and more portable than getopt. It's less powerful, but the power of getopt is rarely useful in a shell script. – Gilles 'SO- stop being evil' Jul 17 '14 at 23:42
  • @Gilles, I recommend getopt only because I'm so familiar with its C counterpart, but I will have to look into getopts. – HalosGhost Jul 17 '14 at 23:43

In a shell script, you call the getopts function in a loop. There is a code example in the dash manual.

Note that your Python code is not correct except in extremely simple cases. It detects an argument -v anywhere on the line, even if it's the argument of another option or after non-option arguments. The correct way to parse options in Python is with argparse or optparse.

|improve this answer|||||
  • I know I normally use optparse (or argparse if available) but I often only need very simple script with just a few options. – Matt3o12 Jul 17 '14 at 23:43

Something like:

for i in "$@"
  [ "$i" = -v ] && verbose=1
|improve this answer|||||
  • 1
    This is analogous to the given Python snippet, but it's not what you should do: it triggers even if -v appears as the argument of another option, or after --. – Gilles 'SO- stop being evil' Jul 17 '14 at 23:40
  • This doesn't seem to be what the user wants. Not all programs have options with value as separate argument and/or choose the usual meaning of --. – vinc17 Jul 17 '14 at 23:50

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.