Bash Best(ish) practices part 4

This is the final post in the series. I will follow up this post by commiting my code to github for easy access.

# bash template

# Print usage information and exit
    echo -e "\n" \
    "usage: ./bashtemplate -o option \n" \
    "\n" \
    "-o <option>    an option\n" \
    "-h             this help\n" \
    "\n" && exit 1

# Options

# Loop through $@ to find flags
while getopts ":ho:" FLAG; do
    case "${FLAG}" in
        o) # Our option
            OPTION="${OPTARG}" ;;
        h) # Print usage information
        [:?]) # Print usage information

# Functions

    echo $(date +"%b %e %T")

error() {
    echo "${NOW}: ERROR: $1"
    exit 1

warning() {
    echo "${NOW}: WARNING: $1"

info() {
    echo "${NOW}: INFO: $1"

# Do something
    info "Doing something..."
    warning "Encountered an anomaly while doing something."

# Program execution

[ "${HELP}" ] && print_usage

if [ ${OPTION} ]
    info "Executing do_something()"

I have removed much of the extraneous stuff from the previous examples as I would like this to be generally useful for writing scripts.

The final element to cover is debugging. In bash the following options are available:

-e Stops execution if any external program returns non-zero.

-x Trace what is being executed.

-n Don’t execute. Useful for syntax errors.

These can also be turned on and off in the script with “set”.

Lets see them in action.


$ bash -x ./bashtemplate
+ getopts :ho: FLAG
+ '[' '' ']'
+ '[' ']'
+ print_usage
+ echo -e '\n' 'usage: ./bashtemplate -o option \n' '\n' '-o <option>    an option\n' '-h             this help\n' '\n'

 usage: ./bashtemplate -o option

 -o <option>    an option
 -h             this help

+ exit 1

-n I introduced a syntax error.

$ bash -n ./bashtemplate
./bashtemplate: line 70: syntax error near unexpected token `else'
./bashtemplate: line 70: `else'

-e I added a grep that would fail followed by an echo statement.

$ bash -e ./bashtemplate

I hope this series has proven useful for someone other than myself, but if it has not I will never know.

Bash Best(ish) practices part 3
Bash Best(ish) practices part 2
Bash Best(ish) practices part 1


2 thoughts on “Bash Best(ish) practices part 4

  1. Pingback: best practice | Kevin's Blog

Leave a Reply

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

You are commenting using your 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