How do I make a Mac Terminal pop-up/alert? Applescript?

Solution 1:

Use osascript. For example:

osascript -e 'tell app "Finder" to display dialog "Hello World"' 

Replacing “Finder” with whatever app you desire. Note if that app is backgrounded, the dialog will appear in the background too. To always show in the foreground, use “System Events” as the app:

osascript -e 'tell app "System Events" to display dialog "Hello World"'

Read more on Mac OS X Hints.

Solution 2:

Use this command to trigger the notification center notification from the terminal.

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

Solution 3:

If you're using any Mac OS X version which has Notification Center, you can use the terminal-notifier gem. First install it (you may need sudo):

gem install terminal-notifier

and then simply:

terminal-notifier -message "Hello, this is my message" -title "Message Title"

See also this OS X Daily post.

Solution 4:

Adding subtitle, title and a sound to the notification:

With AppleScript:

display notification "Notification text" with title "Notification Title" subtitle "Notification sub-title" sound name "Submarine"

With terminal/bash and osascript:

osascript -e 'display notification "Notification text" with title "Notification Title" subtitle "Notification sub-title" sound name "Submarine"'

An alert can be displayed instead of a notification

Does not take the sub-heading nor the sound tough.

With AppleScript:

display alert "Alert title" message "Your message text line here."

With terminal/bash and osascript:

osascript -e 'display alert "Alert title" message "Your message text line here."'

Add a line in bash for playing the sound after the alert line:

afplay /System/Library/Sounds/Hero.aiff

Add same line in AppleScript, letting shell script do the work:

do shell script ("afplay /System/Library/Sounds/Hero.aiff")

List of macOS built in sounds to choose from here.

Paraphrased from a handy article on terminal and applescript notifications.

Solution 5:

This would restore focus to the previous application and exit the script if the answer was empty.

a=$(osascript -e 'try
tell app "SystemUIServer"
set answer to text returned of (display dialog "" default answer "")
end
end
activate app (path to frontmost application as text)
answer' | tr '\r' ' ')
[[ -z "$a" ]] && exit

If you told System Events to display the dialog, there would be a small delay if it wasn't running before.

For documentation about display dialog, open the dictionary of Standard Additions in AppleScript Editor or see the AppleScript Language Guide.