4

I am writing a shell script and wants to pass multiple options in an argument. Is it possible to do that like using getopts?

Requirement example:

./shell.sh -d db1 db2

should pass the values db1 and db2 as the values of the -d option.

tripleee
  • 1,416
  • 3
  • 15
  • 24
Ramesh Kumar
  • 1,770
  • 5
  • 19
  • 29

2 Answers2

4

You can use one option multiple times and collect results in the array:

./shell.sh -d db1 -d db2

Code:

while getopts "d:" opt
do
  case ${opt} in
    d) dbs+=("$OPTARG");;
  esac
done
0

No. But you pass a single argument joined with, for example, a colon; or quoted

./shell.sh -d db1:db2 
./shell.sh -d "db1 db2"

In the first case:

while getopts d: opt; do
    case $opt in
        d) IFS=: read -a dbs <<< "$OPTARG" ;;
    esac
done

In the 2nd case (quoted)

        d) set -f          # turn off filename expansion
           dbs=($OPTARG)   # variable is unquoted
           set +f;;        # turn it back on
glenn jackman
  • 4,630
  • 1
  • 17
  • 20