Generic exit function for iTerm2

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.


Solution 1:

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.

Solution 2:

The section Scripting of the iTerm2 documentation helped me fixing my problem.

In .zshrc I defined the following function:

function exit {
    osascript ~/.zsh/.function_exit.as
}

With ~/.zsh/.function_exit.as as

tell application "iTerm2"
    tell current window to close current session
end tell

Additionally I set the following option in the iTerm2 settings:

enter image description here

enter image description here

Using all the above things together I achieve the following behaviour:

enter image description here

Since this does not depend on the Shell used everything should work perfectly using bash (and the corresponding dot-file).