Skip to content

Instantly share code, notes, and snippets.

@remino
Created May 26, 2022 14:29
Show Gist options
  • Save remino/69c554d71a8cd9dd9f0d01346d407d2a to your computer and use it in GitHub Desktop.
Save remino/69c554d71a8cd9dd9f0d01346d407d2a to your computer and use it in GitHub Desktop.
POSIX-compliant shell script template
#!/bin/sh
# unnamedscript
unnamedscript_main() {
e_args=16
e_no_realpath=17
which realpath 2>&1 > /dev/null \
|| _fatal $e_no_realpath "realpath missing."
scriptpath="` realpath "$0" `"
scriptname="` basename "$scriptpath" `"
scriptdir="` dirname "$scriptpath" `"
#rootdir="` dirname "$scriptdir" `"
while getopts h opt
do
case $opt in
h) unnamedscript_usage && return ;;
*) _invalid_opt ;;
esac
done
shift ` expr $OPTIND - 1 `
[ -z "$cmd" ] && cmd="$1"
shift
[ -z "$cmd" ] && cmd="help"
#[ -z "$cmd" ] && cmd="process"
case "$cmd" in
#process) "unnamedscript_$cmd" "$@" ;;
help|usage) unnamedscript_usage ;;
*) _invalid_cmd ;;
esac
return $?
}
#unnamedscript_process() {
#}
unnamedscript_usage() {
cat <<USAGE
Usage: $scriptname [options] command
Available commands:
help This help screen.
Available options:
-h This help screen.
USAGE
}
_echo() {
echo "$@"
}
_error() {
_echo "$@" >&2
}
_fatal() {
local exitcode
exitcode="$1"
shift
_error "$@"
exit "$exitcode"
}
_invalid_cmd() {
_error "Invalid command: $cmd"
_echo
unnamedscript_usage
exit $e_args
}
_invalid_opt() {
_error "Invalid option: $opt"
_echo
unnamedscript_usage
exit $e_args
}
unnamedscript_main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment