Add shell flags and set long options

This commit is contained in:
gardouille 2023-01-24 18:30:20 +01:00
parent 9976ad1144
commit f8f50b4745
Signed by: gardouille
GPG Key ID: E759BAA22501AF32

View File

@ -7,12 +7,29 @@
#
# !!DATE!!
# }}}
# Flags {{{
## Exit on error {{{
set -o errexit
## }}}
## Exit on unset var {{{
### Use "${VARNAME-}" to test a var that may not have been set
set -o nounset
## }}}
## Pipeline command is treated as failed {{{
### Not available in POSIX sh https://github.com/koalaman/shellcheck/wiki/SC3040
#set -o pipefail
## }}}
## Help with debugging {{{
### Call the script by prefixing it with "TRACE=1 ./script.sh"
if [ "${TRACE-0}" -eq 1 ]; then set -o xtrace; fi
## }}}
# }}}
# Vars {{{
PROGNAME=$(basename "${0}"); readonly PROGNAME
PROGDIR=$(readlink -m $(dirname "${0}")); readonly PROGDIR
PROGDIR=$(readlink --canonicalize-missing $(dirname "${0}")); readonly PROGDIR
ARGS="${*}"; readonly ARGS
readonly NBARGS="${#}"
[ -z "${DEBUG}" ] && DEBUG=1
[ -z "${DEBUG-}" ] && DEBUG=1
## Export DEBUG for sub-script
export DEBUG
@ -43,7 +60,6 @@ OPTIONS:
-h,--help
Print this help message.
HELP
}
# }}}
debug_message() { # {{{
@ -64,7 +80,9 @@ error_message() { # {{{
local_error_code="${2}"
## Print message
printf '%b\n' "ERROR ${PROGNAME}: ${RED}${local_error_message}${RESET}"
printf '%b\n' "ERROR ${PROGNAME}: ${RED}${local_error_message}${RESET}" >&2
unset local_error_message
exit "${local_error_code:=66}"
}
@ -72,13 +90,12 @@ error_message() { # {{{
define_vars() { # {{{
## If my_var_xy wasn't defined (argument) {{{
#if [ -z "${my_var_xy}" ]; then
#if [ -z "${my_var_xy-}" ]; then
### Use default value
#readonly my_var_xy="${MY_VAR_XY_DEFAULT}"
#fi
## }}}
true; ## Remove me
}
# }}}
@ -108,8 +125,15 @@ if [ ! "${NBARGS}" -eq "0" ]; then
manage_arg="0"
## If the first argument ask for help (h|help|-h|-help|-*h|-*help) {{{
if printf -- '%s' "${1-}" | grep --quiet --extended-regexp -- "^-*h(elp)?$"; then
usage
exit 0
fi
## }}}
## If the first argument is not an option
if ! printf -- '%s' "${1}" | grep -q -E -- "^-+";
if ! printf -- '%s' "${1}" | grep --quiet --extended-regexp -- "^-+";
then
## Print help message and exit
printf '%b\n' "${RED}Invalid option: ${1}${RESET}"
@ -120,18 +144,13 @@ if [ ! "${NBARGS}" -eq "0" ]; then
fi
# Parse all options (start with a "-") one by one
while printf -- '%s' "${1}" | grep -q -E -- "^-+"; do
while printf -- '%s' "${1-}" | grep --quiet --extended-regexp -- "^-+"; do
case "${1}" in
-d|--debug ) ## debug
DEBUG=0
debug_message "--- Manage argument BEGIN"
;;
-h|--help ) ## help
usage
## Exit after help informations
exit 0
;;
#-v|--var ) ## Define var with given arg
### Move to the next argument
#shift