Nathan Grigg

Monitor long-running commands: the monitoring script

This is the third in a series of posts describing the system I built to monitor long-running commands.

The second post explained my twait script, which waits for a command in a separate tmux pane or iTerm window to complete, and then exits with the same code.

The easiest way to get notified when twait finishes is to chain the commands:

twait %22; notify

But this ignores the return value, which is a useful part of the notification.

You could solve this by passing the return value as an argument:

twait %22; notify $?

The $? variable contains the return code of the last command.

I mostly use a script called mon that takes the other command as an argument:

mon twait %22

Since mon is running the command, it has access to its exit code. It can also do some prep work before running the command. The downside is that you have to keep the command fairly simple; using pipes, multiple commands, or shell aliases does not work properly.

Here is the code to my monitor script, which lights my blink LED and sends a Pushover notification.

 1 #!/bin/bash
 2 set -eu
 4 function blink() {
 5   blink1-tool -m 0 "$@" > /dev/null
 6 }
 8 blink --rgb 170,170,170
 9 echo "Monitoring $@"
10 "$@"
11 rc=$?
13 case $rc in
14   0)
15     blink --green
16     title="Process succeeded"
17     ;;
18   1)
19     blink --red
20     title="Process failed"
21     ;;
22   *)
23     blink --blue
24     title="Process failed"
25     ;;
26 esac
28 pushover "$title" "Exited with code $rc"

This sets the LED to a dim white at the beginning of the command, prints a message, and then runs the command. The $@ variable contains all of the arguments to the script, which should be the command to run, followed by its arguments. When we are done with the command, we capture the return code.

Depending on the value of the return code, I turn the LED green, red, or blue, and send a message to my phone and watch.

The pushover script uses curl to send a request to the pushover servers.

1 #!/bin/bash
2 set -eu
3 curl -s \
4   --form-string "token=asdfasdfasdfasdf" \
5   --form-string "user=asdfasdfasdfasdff" \
6   --form-string "title=$1" \
7   --form-string "message=$2" \
8   "" > /dev/null

Those are not my token or userid. You have to get your own from pushover.

The final post in this series will show some tmux and AppleScript integrations to make this monitoring easier to launch.