Skip to content

Instantly share code, notes, and snippets.

@davidjeddy
Last active February 1, 2023 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidjeddy/bd243ccb66479fe4a48980cd9b548e7f to your computer and use it in GitHub Desktop.
Save davidjeddy/bd243ccb66479fe4a48980cd9b548e7f to your computer and use it in GitHub Desktop.
Bash / Shell named arguments parsing
#!/bin/bash -e
## Default var values
declare arg1=""
declare arg2=""
## parse positional args
while [ $# -gt 0 ]; do
if [[ $1 == "--help" ]]
then
echo "INFO: Open the script, check the examples section."
exit 0
elif [[ $1 == "--"* ]]
then
if [[ "$2" == "" ]]
then
printf "ERR: Argument '%s' has no value. Exiting with error.\n" "${1}"
exit 1
fi
key="${1/--/}"
declare "$key"="$2"
shift
fi
shift
done
# output positional args
echo "Positional argument key values: arg1: ${arg1} arg2: ${arg2}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment