I was building a bash script and I needed several arguments to make it more versatile (e.g. dry-run). The list of parameters was:

  • help as -h or --help
  • dry run ad -d or --dry-run to go through the motions without actually executing commands
  • keep last N images ad -k num or --keep num to keep last N images (default 5)

As one can see, none of the parameters are compulsory and have default values:

POSITIONAL=()
KEEP_LAST=5
DRY_RUN="F"
HELP="F"

The snipped taking care of my input parameters is:

while [[ $# -gt 0 ]]; do
  key="$1"
  case $key in
    -d|--dry-run)
      DRY_RUN="T"
      shift
      ;;
    -k|--keep)
      KEEP_LAST=$2
      shift
      shift
      ;;
    -h|--help)
      HELP="T"
      shift
      ;;
    *)    # unknown option
      POSITIONAL+=("$1") # save it in an array for later
      shift # past argument
      ;;
  esac
done

The idea is that we loop through all script arguments and shift accordingly. Since the parameters are space separated, we shiftonce for flags without parameters (e.g. --help) and twice for flags with parameters (e.g. --keep).

Once the input parameters are processed, all variables are initialised accordingly.

Note: If you have compulsory parameters, you'll need to check their presence (e.g. via a variable initialised empty) before further processing.

Help

It's good to add a help function. Some languages like python have arguments modules with advanced processing and generate help information by default. Unfortunately, the exclusive-shell variant doesn't do that (unless you want to over-engineer) and you need to do it manually. I ended up having a function like:

function help() {
  echo "Usage:"
  echo "$0 [-d] [-k <num>] [-h]"
  echo "  -d (--dry-run) Executes the script without removing docker images"
  echo "  -k (--keep) <num> Keeps a specified number of old images (default 5)"
  echo "  -h (--help) Display this text"
  exit 0
}

This function can be called from the shell processor:

HELP="F"

case $key in
    # ...
    -h|--help)
      HELP="T"
      shift
      ;;
    # ...
esac

if [ $HELP == "T" ]; then
  help
  exit 0
fi

HTH,