Close Terminal using ‘exit’ when only one window is present, close window otherwise

bashterminal

When I use the Terminal application I want to close it using the command exit if only one Terminal window is open. If more than one window is open, I want to close just the window that executed the exit command.

To achieve this behaviour I use the following function in my .bash_profile

function exit {
    if [ $(who | wc -l) -eq 2 ]; then
        osascript -e 'tell application "Terminal" to quit'
    else
        osascript -e 'tell application "Terminal" to close first window'
    fi
}

Everything works great but the usage of $(who | wc -l) -eq 2 seems to be a bit hacky. In particular this only works if the machine is used by a single user only. Are there any other ways to do the job?

Best Answer

Nice hack!

If you want to cover the edge case where there are multiple people logged in to the Mac and running Terminal then I suggest you change the if test to if [ $(ps | wc -l) -eq 3 ]; which would mean your user had only one process running, the bash shell you want to exit and quit Terminal.

Personally, I use iTerm2 which has a preference (under "General") for "Quit when all windows are closed" so the app takes care of it. If you have got this far with bash I highly recommend iTerm2.

By the way, your method breaks in iTerm2 as it only shows one log in with who no matter the number of windows you have open. My solution can sometimes fail to recognise only one window if you close them quickly in iTerm2 as it takes a couple of seconds for the app to shut down the window server instance.

If you have both Terminal and iTerm running then it breaks everything I could think of as well but you'd only be doing that if you were a constant iTerm2 user answering a question at AskDifferent about Terminal. :)