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?

spraff
  • 32,570
  • 22
  • 121
  • 229
BWHazel
  • 1,474
  • 2
  • 18
  • 31
  • You'll have to use string manipulation, I'm not sure how it works in bash. [This site](http://tldp.org/LDP/abs/html/string-manipulation.html) seems to go through it though. – Griffin Oct 21 '11 at 15:23

2 Answers2

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
ggiroux
  • 6,544
  • 1
  • 22
  • 23
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.

aayoubi
  • 11,285
  • 3
  • 22
  • 20
  • 1
    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. – glenn jackman Oct 21 '11 at 16:18