2

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.

1
  • 3
    Look at the manual for shift. Also look at getopts, which is the right way to do this Commented Apr 30, 2013 at 0:50

1 Answer 1

6

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

Comments

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.