Use Growl to monitor long-running shell commands

Oct 11, '07 07:30:00AM

Contributed by: sapporo

While waiting for long-running shell commands to finish, I often switch to Mail or Safari. Here's how I made Bash notify me via Growl whenever one of those commands finishes. It's a combination of a clever bash script by glyf and Growl's growlnotify shell script. Install Growl, including the growlnotify shell script (found in the Extras directory). Next, download preexec.bash.txt [hints mirror] and save it under ~/.preexec.bash, as an invisible file in your home directory (in case you choose a different filename or location, make sure to adjust it in the following script).

Then add the following code to your ~/.bashrc:

. ~/.preexec.bash

# called before each command and starts stopwatch
function preexec () {
	export PREEXEC_CMD="$BASH_COMMAND"
	export PREEXEC_TIME=$(date +'%s')
}

# called after each command, stops stopwatch
# and notifies if time elpsed exceeds threshold
function precmd () {
	stop=$(date +'%s')
	start=${PREEXEC_TIME:-$stop}
	let elapsed=$stop-$start
	max=${PREEXEC_MAX:-10}
	
	if [ $elapsed -gt $max ]; then
		growlnotify -n "iTerm" -m "took $elapsed secs" ${PREEXEC_CMD:-Some Command}
	fi
}

preexec_install

Now whenever a shell command takes longer than 10 seconds to finish, Growl will notify you about it. To change the threshold temporarily, use export PREEXEC_MAX=20. To change it permanently, just change it in the code you just appended to ~/.bashrc.

[robg adds: I haven't tested this one.]

Comments (22)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20071009124425468