Skip to content

Instantly share code, notes, and snippets.

@dermoth
Last active November 25, 2020 05:48
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 dermoth/21db99452e6e02319df766a97868dcd4 to your computer and use it in GitHub Desktop.
Save dermoth/21db99452e6e02319df766a97868dcd4 to your computer and use it in GitHub Desktop.
Bash + gnu getopt example
#!/bin/bash
set -eu
trap 'echo "$NAME: Failed at line $LINENO" >&2' ERR
NAME=${0##*/}
print_help() {
echo "Usage: $NAME <opts> <args>" >&2
exit 1
}
getopt -T &>/dev/null && rc=$? || rc=$?
if ((rc != 4))
then
echo "This script requires gnu getopt" >&2
exit 1
fi
opts=$(getopt --name "$NAME" --options hf:vd --longoptions help,file:,verbose,debug -- "$@") || print_help
eval set -- "$opts"
declare file verbose=0 debug=0
while (($#))
do
case $1 in
-h|--help) print_help;;
-f|--file) file=$2; shift;;
-v|--verbose) ((++verbose));;
-d|--debug) debug=1;;
--) shift; break;;
# Without "set -e" + ERR trap, replace "false" with an error message and exit.
*) false # Should not happen under normal conditions
esac
shift
done
${file+echo "File is set: '$file'"}
for i in verbose debug
do
echo "${i^} value is ${!i}"
done
if (($#))
then
echo "$# arguments:"
printf " %q\n" "$@"
else
echo "No arguments"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment