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?

link|improve this question

75% accept rate
feedback

1 Answer

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:

#!/bin/bash
while getopts  "abc:" flag
do
  echo "$flag" $OPTIND $OPTARG
done
[~]$./ssc.sh -ab -c file
a 1
b 2
c 4 file
link|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
1  
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
feedback

Your Answer

 
or
required, but never shown

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