-
Notifications
You must be signed in to change notification settings - Fork 4
/
_utils.sh
66 lines (57 loc) · 1.74 KB
/
_utils.sh
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
#!/bin/bash
#
# Printing and error reporting utility functions.
# See the end of this file for usage examples.
#
# You can find more bash utility / helper scripts at [https://github.com/bitrise-io/steps-utils-bash-toolkit](https://github.com/bitrise-io/steps-utils-bash-toolkit)
#
#
# Prints the given command, then executes it
# Example: print_and_do_command echo 'hi'
#
function print_and_do_command {
echo "-> $ $@"
$@
}
#
# This one expects a string as it's input, and will eval it
#
# Useful for piped commands like this: print_and_do_command_string "printf '%s' \"$filecont\" > \"$testfile_path\""
# where calling print_and_do_command function would write the command itself into the file as well because
# of the precedence order of the '>' operator
#
function print_and_do_command_string {
echo "-> $ $1"
eval "$1"
}
#
# Combination of print_and_do_command and error checking, exits if the command fails
# Example: print_and_do_command_exit_on_error rm some/file/path
function print_and_do_command_exit_on_error {
print_and_do_command $@
if [ $? -ne 0 ]; then
echo " [!] Failed!"
if [ "$(type -t ${CLEANUP_ON_ERROR_FN})" == "function" ] ; then
CLEANUP_ON_ERROR_FN
fi
exit 1
fi
}
#
# Check the LAST COMMAND's result code and if it's not zero
# then print the given error message and exit with the command's exit code
#
function fail_if_cmd_error {
last_cmd_result=$?
err_msg=$1
if [ ${last_cmd_result} -ne 0 ]; then
echo "${err_msg}"
exit ${last_cmd_result}
fi
}
# EXAMPLES:
# example with 'print_and_do_command_exit_on_error':
# print_and_do_command_exit_on_error brew install git
# OR with the combination of 'print and do' and 'fail':
# print_and_do_command brew install git
# fail_if_cmd_error "Failed to install git!"