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:
- First it checks whether Terminal is still running. If not, it does nothing.
- 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/