Mac shell trick: have Growl notify you when something happens

August 10, 2011

Let’s say you’re waiting for some event to happen, and that event is detectable in your unix terminal. Examples: a DNS record to propagate (use ping and grep), a blog post to appear in an aggregator (curl and grep), etc. Instead of checking it every minute, you can have your terminal run a loop until it finds the condition you’ve set, and when it does, it’ll notify you with Growl.

I’ll use the DNS-test example here:

To check if domain.com is mapped to 1.2.3.4, we can run,

ping -c1 domain.com | grep "1.2.3.4"; echo $?

Or to check for the appearance of some HTML on a web page, we can do,

curl -s http://somesite.com | grep "some content"; echo $?

The $? at the end checks the exit code - 0 being success, non-0 being error.

Now put that in a loop, running every 30 seconds, with a growl popup when it succeeds:

while true; do
  FOUND=`ping -c1 domain.com | grep "1.2.3.4"; echo $?`; 
  if [[ "$FOUND" -eq "0" ]]; then growlnotify -t "Alert" -m "FOUND" -s; break; fi; 
  sleep 30; 
done

Or in one line,

while true; do FOUND=`ping -c1 domain.com | grep "1.2.3.4"; echo $?`; if [[ "$FOUND" -eq "0" ]]; then growlnotify -t "Alert" -m "FOUND" -s; break; fi; sleep 30; done