Tuesday, December 6, 2016

Bash Script Arugments

I write a lot of bash scripts. It's really out of laziness. Here is a script that allows parsing of specific arguments and passthrough of all other arguments. There are obviously many ways to do this but this is one of the ways that I've found to work best.

# Here is a boolean argument
ARG_NAME_1="-arg1"
ARG_VALUE_1=false

# Here is an argument with a value
ARG_NAME_2="-debug:"
ARG_VALUE_2=""

# Argument parsing.
ARGS=()
for i in "$@"; do
  if [[ "$i" == ${ARG_NAME_1} ]]; then
    ARG_VALUE_1=true
  if [[ "$i" == ${ARG_NAME_2}* ]]; then
        ARG_VALUE_2 =${i:${#ARG_NAME_2}}
  else
    ARGS+=("\"$i\"")
  fi
done

eval AppToLaunch $(IFS=$' '; echo "${ARGS[*]}")


No comments:

Post a Comment