Skip to content

Instantly share code, notes, and snippets.

@brianoflan
Last active January 23, 2017 23:58
Show Gist options
  • Save brianoflan/e4b65bdb8505bc86ed069c51572fa527 to your computer and use it in GitHub Desktop.
Save brianoflan/e4b65bdb8505bc86ed069c51572fa527 to your computer and use it in GitHub Desktop.
basic BASH template (execute, vexecute, die)
#!/bin/bash
cat > functions.sh <<'EOF'
#!/bin/bash
die() {
local exit=$2 ;
echo "$exit" | egrep '^[0-9][0-9]*$' &> /dev/null || exit=1 ;
echo "$1" ;
exit $exit ;
}
execute() { # Notice and say so when a command has a non-zero exit status.
local e=0 ;
# echo "Executing." 1>&2 ;
"$@" || e=$? ;
[[ $e -eq 0 ]] || echo "ERROR: $e executing {$@}." 1>&2 ;
return $e ;
}
vexecute() { # Verbose execute (say the command before running it).
echo "Executing {$@}." 1>&2 ;
execute "$@" ;
}
[[ $DEBUG -lt 2 ]] || echo "Sourced functions.sh ." 1>&2 ;
true ;
#
EOF
# # #
cat > bash_script.sh <<'EOF'
#!/bin/bash
main() {
true ;
# # # TODO: Make the script do something.
}
final() { # Never define final() in functions.sh - only ever define it in an actual script.
[[ $DEBUG -lt 2 ]] || echo "final() { \$?: $? }" ; # Usually shows an exit code of 1 for some mysterious reason. QQQ
echo final_in_script ;
}
trap final EXIT ;
cd $(dirname $0) && main "$@" || { e=$? ; echo "ERROR: '$e' with main in $0." ; exit $e ; } ;
#
EOF
bash bash_script.sh ; echo $?
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment