2021-07-31 22:49:51 -07:00
|
|
|
#!/usr/bin/env sh
|
2024-07-22 05:28:58 -07:00
|
|
|
# compat: +ash +bash +dash +zsh
|
2021-07-31 22:49:51 -07:00
|
|
|
|
2021-08-01 07:35:26 -07:00
|
|
|
argc() { ### @- validate the number of arguments in a function.
|
2021-07-31 22:49:51 -07:00
|
|
|
### ```sh
|
2021-10-13 23:02:51 -07:00
|
|
|
### # usage: myfunc() { argc $# -(eq|le|ge) [0-9] "$0" || return; }
|
2021-07-31 22:49:51 -07:00
|
|
|
###
|
|
|
|
### myfunc() {
|
2021-07-31 23:32:43 -07:00
|
|
|
### # use one of the following:
|
2021-10-13 23:02:51 -07:00
|
|
|
### argc $# -eq N "$0" || return
|
|
|
|
### argc $# -le N "$0" || return
|
|
|
|
### argc $# -ge N "$0" || return
|
2021-07-31 22:49:51 -07:00
|
|
|
### # where N is an integer between 0 and 9.
|
|
|
|
### }
|
|
|
|
### ```
|
|
|
|
|
2021-10-13 23:02:51 -07:00
|
|
|
local usage='usage: myfunc() { %s $# -(eq|le|ge) [0-9] "$0" || return; }\n'
|
2021-07-31 23:32:43 -07:00
|
|
|
|
|
|
|
# note that $zero can be empty, but must be set.
|
2021-10-13 23:02:51 -07:00
|
|
|
if [ $# -ne 4 ] || [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
|
2021-07-31 23:32:43 -07:00
|
|
|
printf "$usage" argc >&2
|
2024-02-24 08:20:47 -08:00
|
|
|
return 1
|
2021-07-31 22:49:51 -07:00
|
|
|
fi
|
|
|
|
|
2021-10-13 23:02:51 -07:00
|
|
|
local argc="$1"; shift
|
2021-07-31 23:32:43 -07:00
|
|
|
local cond="$1"; shift
|
2021-07-31 22:49:51 -07:00
|
|
|
local want="$1"; shift
|
|
|
|
local zero="$1"; shift
|
2021-07-31 23:32:43 -07:00
|
|
|
local many='' plural=''
|
|
|
|
[ "$want" = 1 ] || plural='s'
|
|
|
|
|
2021-10-13 23:02:51 -07:00
|
|
|
if [ "$argc" != "${argc%%[!0-9]*}" ]; then
|
|
|
|
printf "$usage" argc >&2
|
2024-02-24 08:20:47 -08:00
|
|
|
return 1
|
2021-10-13 23:02:51 -07:00
|
|
|
fi
|
|
|
|
|
2021-07-31 23:32:43 -07:00
|
|
|
case "$cond" in
|
2021-10-13 23:02:51 -07:00
|
|
|
('-eq') many='exactly';;
|
|
|
|
('-le') many='at most';;
|
|
|
|
('-ge') many='at least';;
|
|
|
|
(*)
|
2021-07-31 23:32:43 -07:00
|
|
|
printf "$usage" argc >&2
|
2024-02-24 08:20:47 -08:00
|
|
|
return 1;;
|
2021-07-31 23:32:43 -07:00
|
|
|
esac
|
2021-07-31 22:49:51 -07:00
|
|
|
|
|
|
|
case "$want" in
|
2021-10-13 23:02:51 -07:00
|
|
|
([0-9]) :;; # no error, continue.
|
|
|
|
(*)
|
2021-07-31 23:32:43 -07:00
|
|
|
printf "$usage" argc >&2
|
2024-02-24 08:20:47 -08:00
|
|
|
return 1;;
|
2021-07-31 22:49:51 -07:00
|
|
|
esac
|
|
|
|
|
2021-10-13 23:02:51 -07:00
|
|
|
if [ "$argc" "$cond" "$want" ] 2>/dev/null; then
|
|
|
|
:
|
|
|
|
else
|
2021-07-31 23:32:43 -07:00
|
|
|
local err="expected $many $want argument$plural, got"
|
2021-10-13 23:02:51 -07:00
|
|
|
printf '%s: %s %s\n' "$zero" "$err" "$argc" >&2
|
2024-02-24 08:20:47 -08:00
|
|
|
return 64
|
2021-07-31 22:49:51 -07:00
|
|
|
fi
|
|
|
|
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
2021-08-02 13:48:46 -07:00
|
|
|
[ -n "${preload+-}" ] || argc "$@"
|