Instantly share code, notes, and snippets.

Embed
What would you like to do?
bash functions using osascript to use some user interaction on macOS
#!/bin/bash
export PATH=/usr/bin:/bin:/usr/sbin:/sbin
consoleUser() {
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");'
}
displaydialog() { # $1: message
message=${1:-"Message"}
user=$(consoleUser)
if [[ $user != "" ]]; then
uid=$(id -u "$user")
launchctl asuser $uid /usr/bin/osascript <<-EndOfScript
button returned of ¬
(display dialog "$message" ¬
buttons {"OK"} ¬
default button "OK")
EndOfScript
fi
}
displaynotification() { # $1: message $2: title
message=${1:-"Message"}
title=${2:-"Script Notification"}
user=$(consoleUser)
if [[ $user != "" ]]; then
uid=$(id -u "$user")
launchctl asuser $uid /usr/bin/osascript <<-EndOfScript
display notification "$message" with title "$title"
EndOfScript
fi
}
displayfortext() { # $1: message $2: default text
message=${1:-"Message"}
defaultvalue=${2:-"default value"}
user=$(consoleUser)
if [[ $user != "" ]]; then
uid=$(id -u "$user")
launchctl asuser $uid /usr/bin/osascript <<-EndOfScript
text returned of ¬
(display dialog "$message" ¬
default answer "$defaultvalue" ¬
buttons {"OK"} ¬
default button "OK")
EndOfScript
else
exit 1
fi
}
# run all functions
displaydialog "Hello"
name=$(displayfortext "Enter your name:" "$(consoleUser)")
displaynotification "Hello, $name"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment