5th February 2012

Parsing parameters in a BASH shell script

April 7th, 2008 | by dave |

This is a simple alternative to using getopts to parse parameters in a BASH shell script which makes use of the powerful parameter substitution functions in BASH. It should be sufficient for most scripts:


until [[ ! "$*" ]]; do
  if [[ ${1:0:2} = '--' ]]; then
    PAIR=${1:2}
    PARAMETER=`echo ${PAIR%=*} | tr [:lower:] [:upper:]`
    eval P_$PARAMETER=${PAIR##*=}
  fi
  shift
done

The script processes parameters in the format --name=value or --flag.

So, executing: ./example.sh --number=123 --show

Will result in the variable $P_NUMBER being set to “123″ and the variable $P_SHOW evaluating to true as it is set, albeit to a empty value.

Tags: , ,

One Response to “Parsing parameters in a BASH shell script”

  1. By Christopher Lewis on May 26, 2010

    Here are some changes to the parsing functions:

    1) allow only parms that are defined in PARM_ARRAY
    2) Syntax function to print out the function commands.

    #Syntax of script
    syntax() {
    #redirect STDOUT to STDERR so that this can be called via another script
    t=”"
    echo “`basename $0` – Script to xxx1>&2
    echo 1>&2
    echo “`basename $0` –Parm1= –Parm2= [--Parm3] [--Debug]“1>&2
    echo 1>&2
    if [ -n "$1" ] ; then
    echo ” $1″ 1>&2
    fi
    exit 0
    }

    #Function to verify that only paramters in PARM_ARRAY are passed
    PARM_ARRAY=(PARM1 PARM2 PARM3 DEBUG HELP)
    function ParmExists() {
    if [ -z "$1" ]; then
    return
    fi
    for i in ${PARM_ARRAY[@]}; do
    if [ $i == $1 ]; then
    return 1
    fi
    done
    return 0
    }

    #FROM http://www.opensourcery.co.uk/2008/04/parsing-parameters-bash-shell-script/
    # all parms are in the form _PARM
    # Parms not starting with ‘–’ result in error
    # NOTE: PARM_ARRAY + ParmExists are used to prevent extraneous parms i.e. –NotAParm=Anything
    until [[ ! "$*" ]]; do
    if [[ ${1:0:2} = '--' ]]; then
    PAIR=${1:2}
    PARAMETER=`echo ${PAIR%=*} | tr [:lower:] [:upper:]`
    ParmExists $PARAMETER
    retval=$?
    if [ $retval -eq 0 ] ; then
    syntax “Unknown parameter $1″
    fi
    eval _$PARAMETER=’${PAIR##*=}’
    else
    syntax “Invalid parameter $1″
    fi
    shift
    done

    #Show Help
    if [ -n "$_HELP" ] ; then
    syntax
    fi

Post a Comment