Notification From Terminal

Oct 15, 2016

If you are a developer like me, you probably spend lot of time in your terminal. I am sure you’ve encountered situations where you have a long-running process to run in terminal but you don’t have the time to wait for it to finish (e.g., for iOS developer the pod repo update command for CocoaPods takes a long time). Won’t it be nice if your terminal can trigger a notification in notification center when the process is done?

Well there are some solutions for this, like terminal-notifier, but come on, why should we use these external tools if we can build our own in a few simple steps?

The first thing we need is /usr/bin/osascript (documentation), which allows us to run AppleScript from terminal.

For example, the following command triggers a hello world notification:

1

osascript -e'display notification "hello world from terminal!" with title "Hello World :)"'

We can also add a sound effect to it. For example, the following command play the classic glass sound effect with the notification:

1

osascript -e'display notification "hello world from terminal!" with title "Hello World :)" sound name "Glass"'

The sound name "Glass" can be replaced by any sound file name in your System/Library/Sounds folder. Go ahead and play with them :)

You will see that after 3 seconds a notification like this shows up and the glass sound effect will be played.

Hooray! So are we done now? Not yet! aliases are temporary and only work in the terminal session you define them. To make this permanent we can create a .aliases file in your home directory with the aliases you would like to use like this. And if you are using zsh like me you can put it into your .zshrc: