how to get multiple arguments from option in bash script

Issue

#parse options
while getopts ":d:b:n:" opt; do
  case $opt in
    d)
          DIRS+=("$OPTARG")
          echo $DIRS
          ;;
    b)
          PATHBACKUP=$OPTARG
          echo $PATHBACKUP
          ;;
    n)
          FNAME=$OPTARG
          echo $FNAME
          ;;
    :)
          echo "Option -$OPTARG requires an argument." >&2
          error
          exit 1
          ;;
  esac
done
shift $(( OPTIND - 1 ))

This is my code I am trying to store every argument after -d to $DIRS
However, when I echo $DIRS I only get the first argument

Example:

/.script -d /dev /home/work -b /backup
echo $DIRS
echo $PATHBACKUP
> /dev
> /backup

Solution

Use multiple -ds

./script -d /dev -d /home/work -b /backup

otherwise, the first non-option (i.e. /home/work) would stop getopts option processing and -b won’t be considered.

The other alternative would be to use some delimiter like , and parse it yourself

./script -d /dev,/home/work -b /backup

Answered By – Diego Torres Milano

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published