-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathifne
executable file
·83 lines (74 loc) · 1.97 KB
/
ifne
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
76
77
78
79
80
81
82
83
#!/usr/bin/env bash
set -euo pipefail
YP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null && pwd)"
source ${YP_DIR}/sh/common.inc.sh
#- ifne 1.0
## Usage: ifne -- COMMAND
## Poor man's version of moreutils ifne.
##
## -n, --not Reverse operation. Run the command if the standard input is empty.
## -f, --fail Return non-zero exist status if command isn't ran.
## -p, --print-on-fail Print stdin if command isn't ran.
##
## -h, --help Display this help and exit
## -v, --version Output version information and exit
TMP_IFNE=$(mktemp -t yplatform.XXXXXXXXXX)
function on_exit() {
rm -rf ${TMP_IFNE}
}
trap on_exit EXIT
if { getopt --test >/dev/null 2>&1 && false; } || [[ "$?" = "4" ]] || false; then
ARGS=$(getopt -o hvnfp -l help,version,not,fail,print-on-fail -n $(basename ${BASH_SOURCE[0]}) -- "$@") || sh_script_usage
eval set -- "${ARGS}"
fi
SHOULD_BE_EMPTY=false
FAIL_COMMAND=true
PRINT_ON_FAIL=false
while [[ $# -gt 0 ]]; do
case "$1" in
-n|--not)
SHOULD_BE_EMPTY=true
shift
;;
-f|--fail)
FAIL_COMMAND=false
shift
;;
-p|--print-on-fail)
PRINT_ON_FAIL=true
shift
;;
-h|--help)
sh_script_usage
;;
-v|--version)
sh_script_version
;;
--)
shift
break
;;
-*)
sh_script_usage
;;
*)
break
;;
esac
done
# [[ $# -eq 0 ]] || sh_script_usage
cat - > ${TMP_IFNE}
EMPTY=false
cat ${TMP_IFNE} | grep -q . || EMPTY=true
case ${EMPTY}-${SHOULD_BE_EMPTY} in
true-true|false-false)
# we need eval
# shellcheck disable=SC2294
[[ $# -eq 0 ]] || eval "$@"
;;
*)
[[ "${PRINT_ON_FAIL}" = "false" ]] || cat ${TMP_IFNE}
trap - ERR # disable on_error trap
eval "${FAIL_COMMAND}"
;;
esac