Skip to content

Instantly share code, notes, and snippets.

@broilogabriel
Last active July 5, 2022 09:47
Show Gist options
  • Save broilogabriel/fe132eacb1aac61a4851ad8d0d268255 to your computer and use it in GitHub Desktop.
Save broilogabriel/fe132eacb1aac61a4851ad8d0d268255 to your computer and use it in GitHub Desktop.
Snippet for shell script with named arguments
#!/bin/bash
# FROM https://unix.stackexchange.com/a/388038
while [ $# -gt 0 ]; do
if [[ $1 == *"--"* ]]; then
v="${1/--/}"
declare $v="$2"
fi
shift
done
#!/bin/bash
# FROM: https://unix.stackexchange.com/a/580258
while [ $# -gt 0 ]; do
case "$1" in
--days*|-d*)
if [[ "$1" != *=* ]]; then shift; fi # Value is next arg if no `=`
DAYS="${1#*=}"
;;
--select*|-s*)
if [[ "$1" != *=* ]]; then shift; fi
SELECT="${1#*=}"
;;
--help|-h)
printf "Meaningful help message" # Flag argument
exit 0
;;
*)
>&2 printf "Error: Invalid argument\n"
exit 1
;;
esac
shift
done
echo "DAYS $DAYS - select $SELECT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment