Using named arguments in a bash script

Here’s a quick example that can keep you from tracking which order to use when passing arguments.
evaluate_arguments() {
  local i=1 k='' v='' is_named=0
  while [[ ${i} -le ${#} ]]; do
    k=$(eval echo $`echo ${i}`)
    [[ "${k:0:2}" = "--" ]] && k="${k:2}"
    is_named=0
    case "${k}" in
      "foo" | "bar" | "zee" ) is_named=1 ;;
    esac
    if [[ ${is_named} -eq 1 ]]; then
      i=$[${i}+1]
      eval "${k}=$(eval echo $`echo ${i}`)"
    else
      eval "others=\"${others}${k} \""
    fi
    i=$[${i}+1]
  done
  [[ "${others}" != "" ]] \
    && others="${others:0:$[${#others}-1]}" \
    || others='UNSET'
  return 0
}
Basic setup:
set -a nounset
export foo='UNSET' bar='UNSET' zee='UNSET' others=''
Call it:
evaluate_arguments --foo 1 --bar x one two
Examine the results:
cat << EOF
# output: foo='${foo}' bar='${bar}' zee='${zee}' others='${others}'
EOF
# output: foo='1' bar='x' zee='UNSET' others='one two'

About this entry