Search code examples
macososascript

Wait until a certain application has exited, then launch another one


On OS X I want to execute an osascript command that waits until a certain application specified by its full .app path has exited, then start another application, e.g. using /usr/bin/open -n /Applications/MyApp.app.

How to achieve the waiting until the application has exited?


Solution

  • A common approach is to perform a waiting loop, for example with pgrep:

    while pgrep -f /Applications/TextEdit.app 2>/dev/null ; do sleep 1.0 ; done
    

    Unfortunately, this will sleep too much and delay the start of the other application.

    Alternatively, if you know that the application is running, you can use /usr/bin/open:

    open -g -W /Applications/TextEdit.app
    

    Unfortunately, this will open the application if it was not running. You could check it is running before calling /usr/bin/open, but this wouldn't be atomic: it could be closing and the open command could restart it.

    Both can be encapsulated in osascript (although it probably doesn't make much sense).

    osascript -e 'do shell script "while pgrep -f /Applications/TextEdit.app 2>/dev/null ; do sleep 1.0 ; done"'
    osascript -e 'do shell script "open -g -W /Applications/TextEdit.app"'
    

    As a side note: open -W actually performs a kqueue wait (non-polling wait) on the process. There might be other commands invoking kqueue and performing the same task without risking restarting the application. It is quite easy to implement in C.