Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.
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
add comment

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
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
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
add comment

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.