11th March 2010

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: , ,

Post a Comment