Skip to content

Instantly share code, notes, and snippets.

@agateau
Last active January 28, 2022 04:49
Show Gist options
  • Save agateau/dcb50a8eb690a2fb9c65 to your computer and use it in GitHub Desktop.
Save agateau/dcb50a8eb690a2fb9c65 to your computer and use it in GitHub Desktop.
#!/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
@parkercoates
Copy link

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 and cmdline.sh -o=somefile exactly the same as cmdline.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 on bash then the sed invocations could probably be replaced by fancy variable expansion magic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment