Jytug Jytug - 6 months ago 11
Bash Question

Iterating throught bash script arguments

I would like to create a bash script which can be executed as follows:

bash myscript.sh -n n -k k -p1 p1 -p2 p2


where
n,k,p1,p2
are some parameters and
-n, -k, -p1, -p2
indicate which parameters are specified. I would like to be able to parse them. The obvious solution would be to use
getopt
, which doesn't work since there are options with name consisting of more than one character. Iterating tthrought the
$@
variable like this:

for op in $@ ...


is no good either, since I cannot access a neighbor. Is there a way to iterate through the list 'normally', something like this?

for i in {1..$@}; do
case ${$i} in
-n) # do something, accessing ${i+1}
...
esac
done

Answer

You can use shift to remove options after you've processed them.

while (($# > 0)); do
    case $1 in
        -n)  use $2; shift 2;;
        -k)  use $2; shift 2;;
        -p1) use $2; shift 2;;
        -p2) use $2; shift 2;;

        *) echo "Unrecognized option $1" >&2; exit 1;;
    esac
done