Skip to content

Instantly share code, notes, and snippets.

@DanielSmon
Created May 11, 2024 08:06
Show Gist options
  • Save DanielSmon/de1d1d934a21db2d2ab49dd144bc56c8 to your computer and use it in GitHub Desktop.
Save DanielSmon/de1d1d934a21db2d2ab49dd144bc56c8 to your computer and use it in GitHub Desktop.
Bash argument parsing example
#!/bin/bash
set -o errexit # Fail and exit the script immediately if any command fails
set -o nounset # Throw an error if there are unset variables
# Parse arguments (based on https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash)
HARD="false"
VERBOSE="false"
usage_error () { echo >&2 "$(basename ${0}): ${1}"; exit 2; }
assert_argument () { test "${1}" != "${EOL}" || usage_error "${2} requires an argument"; } # TODO: Force boolean
if [ "${#}" != 0 ]; then
EOL=$(printf '\1\3\3\7')
set -- "${@}" "${EOL}"
while [ "${1}" != "${EOL}" ]; do
OPT="${1}"; shift
case "${OPT}" in
-h|--help)
echo
echo "Usage: ${0} (options)"
echo
echo "Options:"
echo " -a, --hard Hard reset, wiping all persisted user data"
echo " -v, --verbose Provide extra output to aid debugging"
echo
exit 1
;;
# Variables
-a|--hard ) HARD="true";;
-v|--verbose ) VERBOSE="true";;
# Arguments processing. You may remove any unneeded line after the 1st.
-|''|[!-]*) set -- "${@}" "${OPT}";; # positional argument, rotate to the end
--*=*) set -- "${OPT%%=*}" "${OPT#*=}" "$@";; # convert '--name=arg' to '--name' 'arg'
-[!-]?*) set -- $(echo "${OPT#-}" | sed 's/\(.\)/ -\1/g') "$@";; # convert '-abc' to '-a' '-b' '-c'
--) while [ "${1}" != "${EOL}" ]; do set -- "$@" "${1}"; shift; done;; # process remaining arguments as positional
-*) usage_error "unknown option: '${OPT}'";; # catch misspelled options
*) usage_error "this should NEVER happen (${OPT})";; # sanity test for previous patterns
esac
done
shift
fi
# Preflight checks
if [ ! -z "$@" ]; then # Abort if bad argument given
echo "Unexpected arguments '${@}'" >&2
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment