MacOS – How to trigger a Notification Center notification from an AppleScript or shell script

applescriptcommand linemacosnotificationsterminal

I'd love to be able to take advantage of 10.8's Notification Center features in AppleScripts and shell scripts I write.

Is there a built-in command or a third-party library I can use from either an AppleScript or shell script?

Ideally the type and icon of the notification could be controlled, but even just the ability to trigger a basic banner with a stock icon (but custom text) would be appreciated.

Best Answer

With Mavericks and later, you can do this using AppleScript's 'display notification':

display notification "Lorem ipsum dolor sit amet" with title "Title"

                          

That's it—literally that simple! No 3rd-party libraries or apps required and is completely portable for use on other systems. 10.9 notification on the top, 10.10 DP in the middle, 10.10 on the bottom.

AppleScript can be run from the shell using /usr/bin/osascript:

osascript -e 'display notification "Lorem ipsum dolor sit amet" with title "Title"'

You can also customise the alert further by adding…

  • a subtitle

    Append 'subtitle' followed by the string or variable containing the subtitle.

    display notification "message" with title "title" subtitle "subtitle"
    

    The above example produces the following notification:

  • sound

    Append 'sound name' followed by the name of a sound that will be played along with the notification.

    display notification "message" sound name "Sound Name"
    

    Valid sound names are the names of sounds located in…

    • ~/Library/Sounds
    • /System/Library/Sounds

Posting notifications can be wrapped as a command-line script. The following code can be run in Terminal and will add a script to /usr/local/bin (must exist, add to $PATH) called notify.

cd /usr/local/bin && echo -e "#!/bin/bash\n/usr/bin/osascript -e \"display notification \\\"\$*\\\"\"" > notify && chmod +x notify;cd -

This is the script that the above will add to notify.

#!/bin/bash
/usr/bin/osascript -e "display notification \"$*\""

Now to display a notification:

notify Lorem ipsum dolor sit amet
sleep 5; notify Slow command finished
Related Question