Last active
August 29, 2015 14:05
-
-
Save viktorbenei/9722b8aea15303ea28e0 to your computer and use it in GitHub Desktop.
Base bash "print and exit on error" utility functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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