Last active
October 7, 2024 07:33
-
-
Save dermoth/21db99452e6e02319df766a97868dcd4 to your computer and use it in GitHub Desktop.
Bash + gnu getopt example
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 -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