Home > Blockchain >  how to get multiple arguments from option in bash script
how to get multiple arguments from option in bash script

Time:11-04

#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

CodePudding user response:

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
  • Related