OSX notifications from your terminal

Example bash function that would show a notification message to the user when the previous command completed

In my normal day to day job many times I need to wait for a very long running shell script to complete. Many times I move back and forward to the terminal window just to see if the command has completed or not.

While waiting for such a script to complete I thought it must be a way to notify to the OSX notification center about the fact that the script completed.

I found a lot of projects out there but was not in the mood of installing another application for just to show such messages, thus I thought there must be a simpler way.

So I ended up writing this simple bash function as my first attempt.


function notify(){
  previousCommand=$(fc -ln -1)
  start=$(date +%s)
  "$@"
  timeTook=$(($(date +%s) - start))
  [ $timeTook -le 5 ] ||
    osascript  \
    -e 'display notification "Finished ['$previousCommand'] took '$timeTook' seconds to finish" with title "Long running command"'
}

But I when invoked I got this message

2017-08-29 12:48:33.481 osascript[59958:4192567] NSNotificationCenter connection invalid
2017-08-29 12:48:33.481 osascript[59958:4192567] Connection to notification center invalid. ServerConnectionFailure: 1 invalidated: 0
2017-08-29 12:48:33.481 osascript[59958:4192567] Connection to notification center invalid. ServerConnectionFailure: 1 invalidated: 0

After some time I found that I need the reattach-to-user-namespace

So installed it by doing brew install reattach-to-user-namespace and changed my original function to

function notify(){
  function notify(){
  start=$(date +%s)
  "$@"
  rc=$?
  previousCommand="$@"
  end=$(date +%s)
   timeTook=$( echo "$end - $start" | bc)
  reattach-to-user-namespace \
    osascript  \
    -e 'display notification "Finished ['$previousCommand'] took '$timeTook' seconds to finish" with title "Long running command"'

  return $rc
}


}

And it worked!!

Now I can execute my scripts and get back a notification when they are finished.

Example:

$ notify make build

[Update]: @stafot suggested an edit to include the execution time as well in the message and looked awesome

Alexandros Sapranidis

Software engineer, keen on wearing many hat, current Senior Software Engineer @Elastic cloud

Athens, Greece http://sapranidis.gr