Clean restart from terminal? In the last several weeks, my OS X 10.8.4 laptop has gotten completely stuck in states where it's impossible to interact with directly. Several times VMWare Fusion's USB shim has broken keyboard input. One time, the system had an apparent race condition between locking the system and drawing the unlock prompt, leaving the GUI completely wedged. These are terrible problems, but there's nothing I can do to fix them.

All I can do is figure out how I can get a clean restart when this happens. I can ssh in to the computer and run any commands, without problem. I don't really trust the system state to be recoverable in either of those states, so I just want a clean reboot.

But shutdown -h now is not a clean reboot. It doesn't do the same things for cleanly shutting down GUI apps that selecting "Restart..." or "Shutdown..." from the apple menu does. It results in data loss because GUI apps weren't shut down cleanly. I could try finding everything I have running in ps, and sending them all SIGTERM. It seems to work, but it's a hugely manual process. I'd love to just tell OS X to do whatever it does when you pick those menu items.

So - is there a utility that does this right? Am I stuck doing it in a manual and error-prone way?
Yeah, ok.  I can solve this with Applescript.  Thanks to patrix for getting me to look in the right direction.

tell application "Finder"
    restart
end tell


Saved as restart.scpt, run with osascript restart.scpt. I've tested running it remotely with the screen locked, and it restarted cleanly perfectly. I need to remember that Applescript exists whenever I want to automate Finder interactions..