Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
myscript [-a a-arg] [-c c-arg] [-b] [-e] somedirectory

Given that I want my shell script be invoked at the command line using the above parameters - where [these brackets] denote that they are optional - what is the best method to parse them?

share|improve this question
up vote 5 down vote accepted

There's a few methods to parse command line arguments. Assuming you're using bash, the least painful way is probably using getopts.

For example:

while getopts  "abc:" flag
  echo "$flag" $OPTIND $OPTARG
[~]$./ -ab -c file
a 1
b 2
c 4 file
share|improve this answer
@John T. Thanks for the answer: solve all except for the last bit: my somedirectory is not an option - how would I get the last parameter (after getopts finishes looping)? – bguiz Mar 12 '10 at 5:13
It will be the last option left in $@ I believe. – John T Mar 12 '10 at 5:24
Got it - shift $(($OPTIND - 1)) was what I was after! – bguiz Mar 12 '10 at 5:45
Excellent! Happy scripting :) – John T Mar 12 '10 at 5:56

Your Answer


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.