Command-Line Exit Function – iTerm2 Guide for Bash and Zsh

bashcommand lineitermzsh

I've recently begun to use iTerm2 instead of the macOS Terminal application and I'm really happy with it. I'm very used to use to exit command to close the instance that currently has focus. With instance I mean one of the following: Tab, Window or Split Panel.

How can I write a function exit that closes the instance that is currently running? The following workaround works for windows but neither for tabs nor for split panels:

function exit {
    osascript -e 'tell application "iTerm2" to close first window'
}

The solution should work with either zsh or bash.

Best Answer

In Terminal, the default setting for handling closed sessions is to leave the window open.

In Preferences > Profiles:

enter image description here

In iTerm2, the default is to close the window

enter image description here

If you disable that option in iTerm2, it should give you the behavior you're looking for.