Shell scripting: Way to parse parameters from command line

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?


Solution 1:

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