Last active
August 29, 2015 14:01
-
-
Save sramam/81fce0f2f7e5d7bde9e6 to your computer and use it in GitHub Desktop.
A mature bash file starter
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 | |
| # allow color coding the console output. | |
| # simple, but effective way to getting visual oomph to the screen | |
| red='\033[0;31m' | |
| green='\033[0;32m' | |
| yellow='\033[0;33m' | |
| white='\033[0;37m' | |
| end_color='\033[0;37m' | |
| base_color=$white | |
| NC='\033[0m' # No Color | |
| # force all normal output white! | |
| echo -e "$base_color " | |
| # the help function | |
| function show_help { | |
| cat << EOF | |
| Usage: ${0##*/} [-hvd] [PARAM] | |
| Some help description... | |
| PARAM a parameter passed to the script | |
| -h this help. | |
| -v verbose mode | |
| -d debug mode | |
| EOF | |
| } | |
| __error_exit=false | |
| function _trap_finish { | |
| local linenum="$1" | |
| if [ $__error_exit = "false" ]; then | |
| echo -e "$green $(basename $0): Success! $end_color" | |
| echo "" | |
| fi | |
| } | |
| function _trap_error { | |
| __error_exit=true | |
| local linenum="$1" | |
| echo -e "$red ERROR $(basename $0):$linenum $end_color" 1>&2 | |
| echo "" | |
| exit $? # actually exit the script. Especially if 'set -e' is not configured | |
| } | |
| function _trap_int { | |
| __error_exit=true | |
| local linenum="$1" | |
| echo "" | |
| echo -e "$yellow '$(basename $0)' was interrupted at $linenum $end_color" 1>&2 | |
| echo "" | |
| exit $? | |
| } | |
| function error_exit { | |
| __error_exit=true | |
| local linenum="$1" | |
| echo "" | |
| echo -e "$red ERROR:$(basename $0):line #$1: $2 $end_color " 1>&2 | |
| echo "" | |
| exit -1 | |
| } | |
| trap '_trap_finish' EXIT | |
| trap '_trap_error ${LINENO}' ERR | |
| trap '_trap_int ${LINENO}' INT | |
| set -e # exit on error | |
| OPTIND=1 # Reset is necessary if getopts was used previously in the script. It is a good idea to make this local in a function. | |
| while getopts "hvd" opt; do | |
| case "$opt" in | |
| h) show_help | |
| exit 0 | |
| ;; | |
| v) set -o;; # enable verbose mode | |
| d) set -x;; # enable debug mode | |
| '?') | |
| show_help | |
| exit 0;; | |
| esac | |
| done | |
| shift "$((OPTIND-1))" # Shift the options and optional --. | |
| param=${1} | |
| if [[ -z $param ]]; then | |
| show_help | |
| error_exit $LINENO "$red PARAM not defined$white" | |
| fi | |
| echo "cmd 1" | |
| echo "cmd 2" | |
| echo "cmd 3" | |
| sleep 20 | |
| #abra # some invalid command | |
| echo "cmd n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment