Reputation: 811
In this bash function I am trying to restart a program:
function restart() { osascript -e "quit app \"$1\""; sleep 1; open -a $1 ; }
osascript -e "quit app \"$1\""
execute OSA script to send a quit signal to an application. Sleep for 1 second to make sure that the application is done quitting. open -a $1
opens the application again.
The function just toggles the application status (i.e., it closes the application if opened, and visa versa). This means that the $1 is replaced with the arg I passes to the function but for some reason either the first or the last command is executed at a time. I would appreciate if somebody showed me how to fix it.
Upvotes: 2
Views: 493
Reputation: 2766
Your solution can be improved in speed and reliability. In your case if the app terminates earlier you are wasting time. As opposed, if the app requires more time to terminate, your script will fail to open a new instance.
Works with OS X 10.11 El Capitan:
restart() {
osascript -l JavaScript <<EOF > /dev/null
var app = Application('$1')
if (app.running()) {
try { app.quit() }
catch (e) {}
}
// Waits at most 4 seconds, checking every 100ms
// if the app has terminated.
for (var i=0; i < 40; ++i) {
delay(0.1)
if (! app.running()) {
app.launch()
break
}
}
EOF
}
restart "$@"
If you are using OSX 10.10 Yosemite simply replace app.running()
with running("$1")
:
ObjC.import('AppKit') // $.NSWorkspace
function running(app) {
var apps = ObjC.unwrap($.NSWorkspace.sharedWorkspace.runningApplications)
for (var i = 0, j = apps.length; i < j; ++i) {
var id = ObjC.unwrap(apps[i].bundleIdentifier)
var name = ObjC.unwrap(apps[i].localizedName)
if (false
|| (id && id.toLowerCase() === app)
|| (name && name.toLowerCase() === app)
) {
return true
}
}
return false
}
Upvotes: 2
Reputation: 811
The function worked as expected when I increased the sleep time to 2 seconds.
function restart() { osascript -e "quit app \"$1\""; sleep 2; open -a $1 ; }
Upvotes: 0