user1976336
user1976336

Reputation: 217

bash script using multiple arguments

I am writing a Bash Script that accepts command line arguments, but not only one at a time, but all of them at a time, using case statements.

Here is my code so far

while [ $# -gt 0 ]
do
    case "$1" in
      -n|--name)
          name="$2"
      ;;
      -s|--size)
          size="$2"
      ;;
      -l|--location)
          location="$2"
      ;;
    esac
done

This code only accepts one at a time, I need it to be able to specify as many as they want.

Upvotes: 2

Views: 3046

Answers (1)

chris
chris

Reputation: 5018

When using getopt you could solve your task as follows:

OPTS=`getopt -o n:s:l: --long name:,size:,location: -- "$@"`
eval set -- "$OPTS"

This splits the original positional parameters into options (that take arguments, indicated by colons) and remaining arguments, both of which might be quoted. Afterwards the result of getopt is evaluated and set -- $OPTS sets the positional arguments $1, $2, $3, ... to what getopt obtained. Afterwards we can just loop through the positional arguments (and stop as soon as we encounter -- which separates options from the remaining arguments to the script).

while true
do
  case "$1" in
    -n|--name)
      name="$2"
      shift 2
      ;;
    -s|--size)
      size="$2"
      shift 2
      ;;
    -l|--location)
      location="$2"
      shift 2
      ;;
    --)
      shift
      break
      ;;
     *)
      echo "Internal error!"
      exit 1
  esac
done

echo -e "name: $name\nsize: $size\nlocation: $location"

Upvotes: 6

Related Questions