MacOS – Automatically quit Terminal when typing exit

applescriptmacossnow leopardterminal

Scenario

I use terminal to SSH a lot, however would like the Terminal App to quit when the last Tab closes using exit. I already have the terminal window itself set to close on successful exit, however Terminal keeps running. I followed Ricky Campbell's tutorial here which uses an AppleScript to quit terminal. The AppleScript works perfectly when running outside of Terminal, however I somehow can't get the trap command to work that needs to be placed in the terminal.

For reference I will post the relevant text here:

Now we need a way to kickoff the script. This can be done with the bash command “trap”, having it listen for the EXIT signal. Since I want this to happen everytime my user opens a shell, I add it to my .profile file. I do this with nano:

$ nano ~/.profile

In this file add the following somewhere. You may need to edit the path to the AppleScript file you created earlier:

trap '/usr/bin/osascript $HOME/Scripts/QuitTerminal.scpt' EXIT

All this does is listen for the EXIT signal within bash and when it gets it, runs the script we created earlier.

Question

How do I go about troubleshooting this problem. For some reason the trap is not firing or working the way it should, even after numerous reboots. Is there an alternative way to get the Terminal App to close when the last tab exits?

Solution

The links provided by Dori led to the solution. The article suggest that the trap command should be in .profile, when in fact it has to be placed in .bashrc. Moving it to the correct script fixed the problem.

Best Answer

The approach given here looks a little simpler—maybe it would work for you?

If you don't want to remember to type "quit" instead of "exit", and you're using bash, just add the following to your .bashrc or other shell startup script:

trap '/usr/bin/osascript -e "tell application \"terminal\" to quit"' 0

What's it do? When the shell receives signal 0 (zero), that is, told to exit, it will execute this command as the last thing it does. This allows your shell, etc, to exit gracefully, and asking Terminal.app to exit via applescript makes sure it does the same. In other words, type 'exit', and your shell exits, then Terminal quits, all cleanly and the way nature intended.

The full thread can be found here.