0
#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
8
  • It is an array, use: echo "${DIRS[@]}" Commented Nov 4, 2022 at 4:59
  • /.script -d /dev -d /home/work -b /backup multiple -d Commented Nov 4, 2022 at 5:01
  • @anubhava i still only get the first argument wether I do "${DIRS[@]}" or echo ${DIRS[*]} Commented Nov 4, 2022 at 5:13
  • the usage method should be only one -d.. unfortunatly Commented Nov 4, 2022 at 5:13
  • 1
    @anubhava: Not a good idea. You would have to apply word splitting to the argument afterwards, which breaks if you want to pass directory names which contain a space. Commented Nov 4, 2022 at 7:29

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

As per the assignment i am not allowed to alter his usage of -d /dev /home. Apparently I somehow loop through the $@ and add it to the DIRS but I cannot find the exact solution as when I do this, it adds every argument of the command line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.