Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
Imho, the best way to do argument parsing in shell scripts is with getopt. See man getopt. –  HalosGhost Jul 17 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 Jul 17 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 at 23:43

2 Answers 2

up vote 2 down vote accepted

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.

share|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 at 23:43

Something like:

for i in "$@"
do
  [ "$i" = -v ] && verbose=1
done
share|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 Jul 17 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 at 23:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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