Saturday, July 26, 2014

BASH: running script with argument equal value ( ./script.sh VAR="value" VAR2="value")

This is an example:

#Parse argument
while [ $# -gt 0 ]; do
 case ${1%%=*} in
  MESSAGE|message)
   MESSAGE=${1#*=}
   ;;
  SPANS|spans)
   SPANS=${1#*=}
   ;;
  NUMBERS|numbers)
   NUMBERS=${1#*=}
   ;;
  ATTEMPT|attempt)
   ATTEMPT=${1#*=}
   ;;
  VERBOSE|verbose)
   VERBOSE=${1#*=}
   ;;
  REPEAT|repeat)
   REPEAT=${1#*=}
   ;;
   *)
   usage
   exit 1
   ;;
 esac
 shift
done


Now you run your script as follow:

./script.sh  MESSAGE="message" SPANS="spans" NUMBERS="numbers" ....

How this works? That's easy!

while [ $# -gt 0 ] - Do, till we are running out of arguments. If we invoke ./script.sh one two three, then our arguments will be:
$0 = name of script ('./script.sh')
$1 = 'one'
$2 = 'two'
$3 = 'three'

On the end of each iteration we cast shift, which removes the first element from arguments array, but not the element's number. Argument numbers will be shifted. So at first cycle $1 will be equal 'one', but at the second iteration $1 will be equal 'two'. Got it?

case ${1%%=*} - In case if the first part (before '=' ) of our argument $1 is equal to (below). If we invoke ./script.sh MESSAGE="sometext", then $1 will be equal 'MESSAGE="sometext"'. Then respectively:

$1 = 'MESSAGE="sometext"'
${1} = 'MESSAGE="sometext"'
${1%%=*}  =  'MESSAGE'
${1#*=} = "sometext"



P.S.

Example of usage function:
usage()
{
        echo "Usage:"
        echo
        echo "$0 MESSAGE=\"message\" SPANS=\"spans\" NUMBERS=\"numbers\" [ATTEMPT=\"attempt\"] [VERBOSE=\"verbose\"] [REPEAT=\"repeat\"]"
        echo "Defaults: ATTEMPT=always VERBOSE=3 REPEAT=1"
        echo "Example: $APP_NAME MESSAGE=\"hello\" SPANS=auto NUMBERS=\"135xxxxxxxx,136xxxxxxxx\""
        echo
}

Look as well at: http://tldp.org/LDP/abs/html/refcards.html#AEN22664

1 comment:

  1. getops example:
    http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

    ReplyDelete