How do I automatically close Terminal.app on exit in OS X Lion?

This option has never closed the Terminal application.

Note that the other options are titled Close the window and Don't close the window (emphasis mine), making it clear that this setting refers to only closing the window, not the entire application.


You could define the following for your shell, e.g. in ~/.bash_profile for bash:

function exit {
    osascript -e 'tell application "Terminal" to quit' 
}

Then add osascript to the list of applications that don't require confirmation before quitting (in Preferences > Settings > Shell). Type exit to exit Terminal, unless there are other tabs with blocking programs running.

You can give it a different name to separate from a regular exit, of course. I like quit for this.


To have Terminal quit after you close the last terminal/shell, you can have your shell run an AppleScript when exiting:

# Quit Terminal when this shell exists if there are no other terminals open.                                                                                                                    
if [ "$TERM_PROGRAM" == "Apple_Terminal" ]; then
    quit_terminal_when_no_terminals_remain() {
        osascript -e 'tell application "Terminal" to if running and (count every tab of every window whose tty is not "'"$(tty)"'") is 0 then quit'
    }
    trap quit_terminal_when_no_terminals_remain EXIT
fi

The test for Apple_Terminal ensures this code only takes effect when running inside Terminal.

Since this runs asynchronously, the script may run before or after the terminal containing it is closed (though it usually runs after), and if this terminal is closed because the user quit Terminal, Terminal may no longer be running when the script runs, therefore:

  1. First it checks whether Terminal is still running. If not, it does nothing.
  2. It only quits if there are either no terminals open or only the one for the current tty. It checks whether there are any tabs other than the one for the tty device to which the current shell is connected "$(tty)".

Note that if you invoke any other shell code that traps EXIT, these will interfere with one another. The solution is to create another function that calls the others and "trap the_other_function EXIT" to invoke everything when the shell exits.

By the way, as always, if this functionality is important to you please file an enhancement request with Apple. Ask for a preference setting to make Terminal quit when there are no more windows open: https://bugreport.apple.com/