-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhavecmd
executable file
·75 lines (63 loc) · 1.61 KB
/
havecmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env bash
# Often used like:
# havecmd -V 'Install from github.com/...' some_command || exit $?
# To exit in my shell scripts if a required command isn't found
#
# this extends 'command -v' to optionally report errors
set -e
main() {
local usage missing_command_text report_missing
# shellcheck disable=SC2016
usage='havecmd [-v] [-V MISSING_COMMAND_TEXT] COMMAND
Provide [-v] (verbose) to report to the user if the
COMMAND is not found on their $PATH
If the COMMAND is not found, -V MISSING_COMMAND_TEXT can be provided
to provide a custom error to the user (e.g. describe how to install/configure)
To enable verbose through a environment variable:
export HAVECMD_REPORT=1
havecmd awk || exit $?
havecmd evry -V "Install from ..." || exit $?'
report_missing=0
missing_command_text=''
[[ -n "$HAVECMD_REPORT" ]] && report_missing=1
[[ "$1" == "--help" ]] && {
printf "%s\n" "$usage"
exit 10
}
while getopts "hV:v" opt; do
case "$opt" in
h)
printf "%s\n" "$usage"
exit 10
;;
v)
report_missing=1
;;
V)
report_missing=1
missing_command_text="$OPTARG"
;;
?)
printf 'Unknown flag: %s\n' "$opt"
printf "\n%s\n" "$usage"
return 10
;;
esac
done
shift "$((OPTIND - 1))"
COMMAND="${1:?Must provide COMMAND to check as argument}"
if command -v "${COMMAND}" >/dev/null 2>&1; then
exit 0
else
if ((report_missing)); then
printf "havecmd: Could not find '%s' on your \$PATH." "$COMMAND" >&2
if [[ -n "$missing_command_text" ]]; then
echo -e " ${missing_command_text}" >&2
else
echo # fix cursor location
fi
fi
exit 2
fi
}
main "$@" || exit $?