7

When writing Bash scripts, how can I obtain a value from the command-line when provided as part of option flags in the command line?

For example in the following:

./script --value=myText --otherValue=100

How could I store the myText and 100 values in the variables $text and $num?

1
  • You'll have to use string manipulation, I'm not sure how it works in bash. This site seems to go through it though. Commented Oct 21, 2011 at 15:23

2 Answers 2

2

Use getopts.

#!/bin/bash

while getopts ":a:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done
Sign up to request clarification or add additional context in comments.

Comments

0

If case you really need to use --longoption, if you can stick with a single char option -a, stick with what spraff said. You can do the following:

#!/bin/bash
main()
{
    [[ $1 =~ "--value=(.*)" ]] && echo "First arg: $1"
    value=${BASH_REMATCH[1]}

    [[ $2 =~ "--otherValue=(.*)" ]] && echo "Second arg: $2"
    other=${BASH_REMATCH[1]}

    echo $value
    echo $other

    #doYourThing

    return 0

}

main $*

Make sure you are running bash 3.0.

$ echo $BASH_VERSION
3.00.16(1)-release

If you have bash 4.x, do not put double quotes around the regex patterns.

1 Comment

Better be flexible about the order of options -- don't assume "--value" must be the first option. Use a while loop and shift the matched options.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.