Macos – How to identify the terminal from a script

iterm2macosterminal.app

And don't say "$TERM" – it's always xterm.

How can a bash script tell what terminal it's running in, specifically whether it's iTerm, Terminal.app, or actually an xterm?

I ask because reset does not work¹ out of the box on Terminal.app and iTerm2. iTerm2, however, does recognize an escape sequence for doing a terminal reset (\x1b]50;ClearScrollback\x07), and if I could detect it, I could override reset with an alias that does the right thing. AFAICT, Terminal.app lacks a reset sequence, and people resort to ridiculous tom-hackery to hack around that.

My end goal here is to have reset work the same whether I'm working on OS X or Linux, working locally or remotely through SSH. (I don't want to have to try to remember which, and it's useful to do reset && command-that-outputs-a-bunch and have up-enter work.) Terminal.app and iTerm are throwing a wrench in this plan by not implementing reset correctly.

This means that simply overriding reset isn't quite it: if I'm on a Linux machine, it needs to know whether I'm using gnome-terminal or iTerm in order to send the right escape sequence.

Is there any way (even if I need an ioctl) to ask the terminal what it really is?

¹For the purposes of this question, reset should clear the screen, reset the cursor, and wipe the scrollback buffer.

Best Answer

Use $TERM_PROGRAM.

iTerm sets it to iTerm.app, and Terminal.app to Apple_Terminal.

Related Question