PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 19, 2022

[FIXED] how to get multiple arguments from option in bash script

 November 19, 2022     bash, linux, scripting, shell     No comments   

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
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing