ding: Audio Feedback for Exit Codes

October 28, 2022

Do you babysit long-running applications?

You could display a desktop notification, but it’s even nicer (and mouseless) to know how things went without looking.

My use case

I run mix test in another tmux window; it’s “offscreen” for all intent and purposes.

I use entr to trigger mix test: my tests will run when files change.

> git ls-files | entr mix test

# if `git ls-files` is too large, I use a filter
> git ls-files | rg some-filter | entr mix test

I want to know: did the tests pass?

Ding

> ding successful-command             # e.g. ding echo hello
# plays good sound

> ding UNsuccessful-command           # e.g. ding rm doesnt-exist.txt
# plays sad sound

> ding
# plays good sound

That last one is more useful than it looks: if you already started something and realize it’s going to take a while; type ding and it will execute when the first command finishes.

All together now:

> git ls-files | entr ding mix test

Simple Enough

ding is a simple script:

Here’s the script as of the writing of this post:

#!/bin/bash

play_sound() {
  if ! command -v afplay &>/dev/null; then
    echo >&2 "ding: cannot play sound!"
    return
  fi

  if [ "$1" -eq 0 ]; then
    afplay "/System/Library/Sounds/Purr.aiff"
    return
  fi

  afplay "/System/Library/Sounds/Basso.aiff"
}

"$@"
lastexit=$?

play_sound "$lastexit" &
exit "$lastexit"

Both afplay and the .aiff files assume a macOS environment.

But there’s so little logic here, it’s easy to adapt to your own needs.

Discuss on Twitter