Bash Boilerplate

I’ve ended up doing a lot of bash scripting lately and am really shocked at how difficult it is to sort out all most mundane things like handling long and short options and some other cases like ensuring the script is run as root. So here is my bash boilerplate; 45 lines of time and sanity saving bash script. It has been lovingly assembled in Franenstinian fashion from about a dozen blogs and stackoverflow answers and owes a great debt to missiondata’s excellent post on getopt. Thank you internet.

I have several scripts using variations on this now that I use reasonably regularly and its a real time saver to use this as my starting point. If you notice a mistake or something that is flat out a bad idea please let me know. I’d like to make this as solid as possible.


#!/usr/bin/env bash
# set the script to exit immediately on error
set -e

usage(){
cat <<'EOT'
Call this script with...
EOT
exit 0;
}

# exit if there are no arguments
[ $# -eq 0 ] && usage

set -- `getopt -n$0 -u -a --longoptions "help dogs: cats:" "hd:c:" "$@"`

# $# is the number of arguments
while [ $# -gt 0 ]
do
case "$1" in
-d|--dogs) dogs="$2"; shift;;
-c|--cats) cats="$2"; shift;;
-h| --help) usage;;
--) shift;break;;
*) break;;
esac
shift
done

cleanup_before_exit () {
# this code is run before exit
echo -e "Running cleanup code and exiting"
}
# trap catches the exit signal and runs the specified function
trap cleanup_before_exit EXIT

# if this script needs to be run as root
# we can check like this:
# if [ ! `id -u` -eq 0 ]; then
#  echo "You need to call this script using sudo."
#  exit 1
# fi

# OK now do stuff
echo "$cats and $dogs living together, mass hysteria!"

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s