This template script was retrieved from BigSmoke's Blog on 18 February 2011. It was originally authored by [Wiebe Cazemier](mailto:Wiebe Cazemier wiebe@halfgaar.net) and he deserves the credit. I am putting it on gist.github.com so I don't lose it, mostly, although I hope someone else is able to find it as useful as I do.
Created
February 18, 2011 21:59
-
-
Save rtlong/834497 to your computer and use it in GitHub Desktop.
Template bash script, for when you need something over-engineered.
This file contains 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 | |
# | |
# Author: YOUR NAME (email) | |
# | |
# Place a small description of your script here. | |
# Hack prevention | |
PATH="/sbin:/usr/sbin:/bin:/usr/bin" | |
# Error codes | |
wrong_params=5 | |
interrupted=99 | |
default_error=1 | |
# Function to echo in color. Don't supply color for normal color. | |
echo_color() | |
{ | |
message="$1" | |
color="$2" | |
red_begin="\033[01;31m" | |
green_begin="\033[01;32m" | |
yellow_begin="\033[01;33m" | |
color_end="\033[00m" | |
# Set color to normal when there is no color | |
[ ! "$color" ] && color_begin="$color_end" | |
if [ "$color" == "red" ]; then | |
color_begin="$red_begin" | |
fi | |
if [ "$color" == "green" ]; then | |
color_begin="$green_begin" | |
fi | |
if [ "$color" == "yellow" ]; then | |
color_begin="$yellow_begin" | |
fi | |
echo -e "${color_begin}${message}${color_end}" | |
} | |
end() | |
{ | |
message="$1" | |
exit_status="$2" | |
if [ -z "$exit_status" ]; then | |
exit_status="0" | |
fi | |
if [ ! "$exit_status" -eq "0" ]; then | |
echo_color "$message" "red" | |
else | |
echo_color "$message" "green" | |
fi | |
if [ "$exit_status" -eq "$wrong_params" ]; then | |
dohelp | |
fi | |
exit $exit_status | |
} | |
# Define function to call when SIGTERM is received | |
trap "end 'Interrupted' $interrupted" 1 2 3 15 | |
dohelp() | |
{ | |
cat <<END-OF-HELP-MESSAGE | |
Usage: $0 --option1 value1 | |
or: $0 value1 | |
[SHORT DESCRIPTION OF THIS FORM] | |
[DESCRIPTION HERE] | |
END-OF-HELP-MESSAGE | |
# Exit because you don't want the script to do anything after displaying help | |
exit | |
} | |
# If you want to capture mandatory arguments that should be given first, do so with something like this. | |
# mandatory_option1=$1 | |
# mandatory_option2=$2 | |
# shift 2 | |
while [ -n "$*" ]; do | |
flag=$1 | |
value=$2 | |
case "$flag" in | |
"--option1") | |
option1=$value | |
shift | |
;; | |
"--help") | |
dohelp | |
;; | |
"--") | |
break | |
;; | |
*) | |
end "unknown option $flag. Type --help" "$wrong_params" | |
;; | |
esac | |
shift | |
done | |
if [ -z "$option1" ]; then | |
end "option1 not given" $wrong_params | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment