Wednesday, July 29, 2009

Get notified when a command finishes

I tried for quite a while (I'm not really a bash expert) unsuccessfully building up a mechanism to notify me when a command has finished. I wanted more than a simple notification. I wanted it to tell me which command it was and its exit status. So I tried the following script:

$ cat saydone

#!/bin/bash
if [ "$1" != "" ]; then
$*;
fi
if [ $? = 0 ]; then
notify-send "Done: $*";
else
notify-send -urgency=critical "Failed: $*";
fi


Now I could type $ saydone command or $ command ; saydone where the last one would miss the command typed. That worked well until I found out it does not handle aliases. I've tried outputting the command to a temporary script file preceded by shopt -s expand_aliases (as pointed here) which didn't work for some reason I don't know.

Then I started playing around with history which (apparently) does not work inside bash scripts. Then I ran across this post which inspired me to create my final version:

alias saydone="notify-send \"\`history 1\`\""

Which gets you a nice simple notification:




And if you are looking for something fancier, you can add the following to your .bashrc:

alias saydone='if [ $? = 0 ]; then
notify-send Successed "`history 1 | cut -d\; -f1 | cut -b8-`" ;
else
notify-send --urgency=critical Failed "`history 1 | cut -d\; -f1 | cut -b8-`" ;
fi'


And type $ ls /bogus ; saydone to get:

No comments:

Post a Comment