UNIX/Linux

Tips For Robust Bash Scripts

Here are a couple of quick tips for writing more robust shell scripts from my last 10 years of working with bash.

Tip 1: Use "set -e"

This will cause your script to exit if an error occurs.

#! /bin/sh
set -e
 
false ;# ops! exit here

If errors are OK, you can add "|| true" so that it'll continue.

catalina-restart.sh

A short script to stop Tomcat, and then restart it.

#! /bin/sh
set -eu
 
while [ $(netstat -na | grep -c 8080) -ne 0 ] ; do
        echo "Stopping Catalina..."
        catalina.sh stop
        sleep 3s
done
 
catalina.sh jpda start

Snippet: grep-jar.sh

First draft of a script to grep for string inside jar (i.e. zgrep). I'm pretty sure there's a more elegant way of doing this, but this is functional.

Snippet: which-jar.sh

I seem to spend a lot of time trying to find files in jars, so I wrote a script a while ago to do this.

Robust Cronjobs

Cron jobs were the bane of my life. They were fragile, unreliable, time consuming to test, hard to fix. If some failed then they were impossible to re-run. No performance metrics were collected and no monitoring was undertaken. Ultimately they were costly to write, and as no one knew what they did, costly to maintain.

Here's some quick tips on writing robust cron jobs.

Subscribe to RSS - UNIX/Linux