John Watson

Hello! My name is Watson and I’m a freelance web developer. I create web sites using the latest tech for clients of all sizes. Contact me and I’ll help you build your dream project.

Shell script that does something only when status changes

I needed a shell script that runs every 5 minutes but I only wanted it to do something when a status changes. In this case, I wanted it to log some information to the system log but I didn’t want it to fill up the log with redundant entries. Here’s the pattern I came up with.

My true condition was checking the exit code of a command (e.g. $? -eq 0) but it could be anything. The key is that a temporary file (LOCKFILE) is created for one status and is deleted for the other status. This allows the script to keep track of state between runs. This script only differentiates between two statuses but it wouldn’t be difficult to adapt this to track changes between multiple states (store the current state in LOCKFILE).

Note, the way this is written, the true action will always be executed once after the system is booted.



if [ some condition is true ]
    echo Status 1
    if [ ! -e $LOCKFILE ]
        logger -t $TAG "Message for status 1"
        touch $LOCKFILE
    echo Status 2
    if [ -e $LOCKFILE ]
        logger -t $TAG "Message for status 2"
        rm $LOCKFILE