xenefix
6/29/2018 - 12:34 PM

Bash: Argument Parsing

Bash: Argument Parsing

#!/bin/bash
PARAMS=""
while (( "$#" )); do
  case "$1" in
    -1|--flag-with-argument-1)
      F_ARG_1=$2
      shift 2
      ;;
    -2|--flag-with-argument-2)
      F_ARG_2=$2
      shift 2
      ;;
    --) # end argument parsing
      shift
      break
      ;;
    -*|--*=) # unsupported flags
      echo "Error: Unsupported flag $1" >&2
      exit 1
      ;;
    *) # preserve positional arguments
      PARAMS="$PARAMS $1"
      shift
      ;;
  esac
done
# set positional arguments in their proper place
eval set -- "$PARAMS"
echo $F_ARG_1
echo $F_ARG_2