Gracefully Close an Application from the Command Line in Mac OS X
Quitting apps gracefully is typically done through the appropriate application menu by choosing “Quit”, but the Mac GUI is obviously inaccessible from the command line of Mac OS X. So when most command line users are confronted with the need to exit an application, they wind up using the ‘kill’ command to terminate the process and forcibly quit the app, rather than issuing a ‘soft’ kill. The obvious problem with terminating an app is that while it does exit the application, you may lose data in that process, and even session restoration caches may not be adequate to restore the data. Thus, whenever possible, it’s usually best for users to gracefully quit an application instead.
Though it’s not particularly well known, you can send a standard quit signal to any Mac OS X GUI app from the command line with the assistance of the osascript command. It’s fairly easy to use, and that’s what we’ll cover here.
How to Gracefully Quit Apps from the Terminal in Mac OS X with osascript
Again, this will issue a standard quit signal to an application, rather than a kill (terminate) signal. That also means the target application won’t forcibly exit if there is unsaved data without prompting the user for input (unless you have auto-save setting enabled for Mac OS X and the application doesn’t prompt the user as a result).
The basic syntax to send a standard quit signal to a GUI application in Mac OS X from Terminal is as follows:
osascript -e 'quit app "APPLICATIONNAME"'
For example, to quit Calendar from the command line, replace APPLICATIONNAME with “Calendar”
osascript -e 'quit app "Calendar"'
Because Calendar syncs and doesn’t have a save option, you won’t be presented with the standard save dialog when trying to close the app. With apps that do have save options and when Mac OS X has auto-save disabled, the save dialog box will be summoned as usual.
Another advantage to using osascript to close apps gracefully is that you can provide an actual application name, which is much easier to remember and quite a bit more user friendly than relying entirely on process ID numbers that go with the kill command. Note that modern versions of Mac OS X offer an improved kill command that is more user friendly, known as pkill.
You could use this in a bash script to close out applications from the command line, or even modify it to behave similarly to the “Quit All Open Apps” with Automator trick we covered a while back.