Tuesday 6 January 2015

bash command line parsing

We want to be able to mix both optional flags, optional arguments and positional arguments

optional flags: getopts character, not followed by a ':'
optional arguments: getopts character, followed by a ':' (which means "take an argument"
positional arguments: after the getopts, use $OPTIND which is the index of the last option getopts parsed.

$ script.sh [options] ARG1 ARG2

#!/bin/bash

usage() 

    echo "Usage: $0 [-a foo] [-b] ARG1 ARG2" 1>&2;
    exit 1
}

while getopts ":a:bh" o; do
    case "${o}" in
        a) a=${OPTARG};;
        b) b=YES;; # turn on flag
        h) usage ;; # display help
    esac
done

# store positional arguments
ARG1=${@:$OPTIND:1}
ARG2=${@:$OPTIND+1:1}

# check positional arguments have been supplied
if [ -z "${ARG1}" ] || [ -z "${ARG2}" ]; then
    usage
fi

# display the results
echo a=${a}
echo b=${b}
echo ARG1=${ARG1}
echo ARG2=${ARG2}

No comments:

Post a Comment