Last active
February 1, 2023 13:14
-
-
Save davidjeddy/bd243ccb66479fe4a48980cd9b548e7f to your computer and use it in GitHub Desktop.
Bash / Shell named arguments parsing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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