Skip to main content

Example of how to parse options with bash getopt.

#!/usr/bin/env bash

OPTS=`getopt -o vhns: --long verbose,dry-run,help,stack-size: -n 'options-test.sh' -- "$@"`
if [ $? != 0 ]; then
    echo "Failed parsing options." >&2
    exit 1
fi

#eval set -- "$OPTS"

VERBOSE=false
HELP=false
DRY_RUN=false
STACK_SIZE=0

while true; do
    case "${1}" in
        -v | --verbose    ) VERBOSE=true; shift ;;
        -h | --help       ) HELP=true; shift ;;
        -n | --dry-run    ) DRY_RUN=true; shift ;;
        -s | --stack-size ) STACK_SIZE="$2"; shift; shift ;;
                       -- ) shift; break ;;
                        * ) break ;;
                        #* ) if [ -z "$1" ]; then break; else echo "$1 is not a valid option"; exit 1; fi;; to
    esac
done

echo VERBOSE=$VERBOSE
echo HELP=$HELP
echo DRY_RUN=$DRY_RUN
echo STACK_SIZE=$STACK_SIZE

#
# Iterate over rest arguments called $arg
for arg in "${@}"; do
    # Your code here (remove example below)
    echo "${arg}"
done