Skip to content

Instantly share code, notes, and snippets.

@viktorbenei
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viktorbenei/9722b8aea15303ea28e0 to your computer and use it in GitHub Desktop.
Save viktorbenei/9722b8aea15303ea28e0 to your computer and use it in GitHub Desktop.
Base bash "print and exit on error" utility functions
#!/bin/bash
#
# Prints the given command, then executes it
# Example: print_and_do_command echo 'hi'
#
function print_and_do_command {
echo " -> $ $@"
$@
}
#
# Print the given command, execute it
# and exit if error happened
function print_and_do_command_exit_on_error {
print_and_do_command $@
if [ $? -ne 0 ]; then
echo " [!] Failed!"
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 {
local last_cmd_result=$?
local error_msg="$1"
if [ ${last_cmd_result} -ne 0 ]; then
echo " [!] ${error_msg}"
exit ${last_cmd_result}
fi
}
# 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!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment