#!/bin/bash
# How to specify the same option multiple times using Bash - case B
# https://sleeplessbeastie.eu/
# milosz at sleeplessbeastie.eu

# bash case-b.sh -p "first argument" "second one" -p "third one"

# usage info
usage(){
  echo "Usage:"
  echo "  $0 -p argument-a argument-b argument-x"
  echo ""
  echo "Options:"
  echo "  -p argument : set multiple arguments"
  echo ""
  exit
}

# parse options and arguments
while getopts "p:" option; do
  case $option in
    "p")
      arguments+=("$OPTARG")
      while [ "${OPTIND}" -le "$#" ] && [ "${!OPTIND:0:1}" != "-" ]; do 
        arguments+=("${!OPTIND}")
        OPTIND="$(expr $OPTIND \+ 1)"
      done
      ;;
    *)
      usage
      ;;
  esac
done

# no options were provided or there was a mistake
if [ "${OPTIND}" -eq "1" ] || [ "${OPTIND}" -le "$#" ]; then
  usage
fi

echo "Provided arguments:"
for argument in "${arguments[@]}"; do
  echo "  \"${argument}\""
done
