Skip to content

Instantly share code, notes, and snippets.

@nirev
Last active February 22, 2021 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nirev/d3d6a6c4b953967f5e98430d6ac90d27 to your computer and use it in GitHub Desktop.
Save nirev/d3d6a6c4b953967f5e98430d6ac90d27 to your computer and use it in GitHub Desktop.
dialog notifications in OSX
# Get the logged in user's name
CURRENT_USER="$(python -c 'from SystemConfiguration import SCDynamicStoreCopyConsoleUser; import sys; username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0]; username = [username,""][username in [u"loginwindow", None, u""]]; sys.stdout.write(username + "\n");')"
# Get information necessary to display messages in the current user's context.
USER_ID=$(id -u "$CURRENT_USER")
if [[ "$OS_MAJOR" -eq 10 && "$OS_MINOR" -le 9 ]]; then
L_ID=$(pgrep -x -u "$USER_ID" loginwindow)
L_METHOD="bsexec"
elif [[ "$OS_MAJOR" -eq 10 && "$OS_MINOR" -gt 9 ]]; then
L_ID=USER_ID
L_METHOD="asuser"
fi
# Call osascript
launchctl "$L_METHOD" "$L_ID" /usr/bin/osascript -e "<YOUR DIALOG>"

Hello World

$ osascript -e 'display dialog "Hello from bash!"'

The display dialog AppleScript command is documented in the "StandardAdditions" dictionary. You can see it when you choose Open Dictionary… from the File Menu in Script Editor. Then select the "Scripting Additions.osax" dictionary and choose the "User Interaction" category.

Buttons

One button

basic example:

$ osascript -e 'display dialog "Just accept it!" buttons {"Accept"} default button 1'
button returned:Accept

parsing output:

$ osascript -e 'button returned of (display dialog "Just accept it!" buttons {"Accept"} default button 1)'
Accept

Yes / No

$ osascript -e 'button returned of (display dialog "Are you sure!?" buttons {"No", "Yes"})'
Yes

Three buttons

(three is the maximum)

$ osascript -e 'button returned of (display dialog "The answer is C" buttons {"A", "B", "C"} default button 3'
C

Adding icons

$ osascript -e 'display dialog "Hello" with icon note'

You can also use stop or caution for different icons or add a path to an icns file:

$ osascript -e 'display dialog "Hello!" with icon POSIX file "/Applications/Notes.app/Contents/Resources/AppIcon.icns"'

Asking for Input

$ osascript -e 'display dialog "Who are you?" default answer "nobody"'
button returned:OK, text returned:nobody

$ osascript -e 'text returned of (display dialog "Who are you?" default answer "nobody")'
nobody

Notifications

$ osascript -e 'display notification "Hello, again" with title "Hello"'

references

[1] https://scriptingosx.com/2018/08/user-interaction-from-bash-scripts/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment