Last active
January 28, 2022 04:49
-
-
Save agateau/dcb50a8eb690a2fb9c65 to your computer and use it in GitHub Desktop.
This file contains 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 | |
set -e | |
PROGNAME=$(basename $0) | |
die() { | |
echo "$PROGNAME: $*" >&2 | |
exit 1 | |
} | |
usage() { | |
if [ "$*" != "" ] ; then | |
echo "Error: $*" | |
fi | |
cat << EOF | |
Usage: $PROGNAME [OPTION ...] [foo] [bar] | |
<Program description>. | |
Options: | |
-h, --help display this usage message and exit | |
-d, --delete delete things | |
-o, --output [FILE] write output to file | |
EOF | |
exit 1 | |
} | |
foo="" | |
bar="" | |
delete=0 | |
output="-" | |
args=() | |
while [ $# -gt 0 ] ; do | |
case "$1" in | |
-h|--help) | |
usage | |
;; | |
-d|--delete) | |
delete=1 | |
;; | |
-o|--output) | |
output="$2" | |
shift | |
;; | |
-*) | |
usage "Unknown option '$1'" | |
;; | |
*) | |
args=("${args[@]}" "$1") | |
;; | |
esac | |
shift | |
done | |
cat <<EOF | |
foo=$foo | |
bar=$bar | |
delete=$delete | |
output=$output | |
EOF | |
for arg in "${args[@]}" ; do | |
echo "'$arg'" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice template! I added an extra case clause to support using an optional equal sign to pass arguments to a flag. For example, to treat
cmdline.sh --output=somefile
andcmdline.sh -o=somefile
exactly the same ascmdline.sh --output somefile
.When it encounters what looks like a flag containing an equals sign, it just just splits it into the flag and the argument, shifts it off and shifts the separate parts back on again and continues looping. It's a bit hacky, but it seems to work. I tend to aim for
sh
compatibility, but if one was okay with depending onbash
then thesed
invocations could probably be replaced by fancy variable expansion magic.