Get Terminal Emulator Name Inside Shell Script

linuxprocessesshell-scriptterminalterminal-emulator

I have used pstree to find the name of the parent emulator of running shell script using something similar to the following:

pstree -s $PPID | awk -F '---' '{print $6}'

This works in my current system. I tested in mate-terminal and xterm but not sure if this will work on other Linux systems/platforms and other terminals. Is there a better/tidier (more portable way) way of achieving this?

Best Answer

ps -o comm= -p "$(($(ps -o ppid= -p "$(($(ps -o sid= -p "$$")))")))"

May give you good results. It gives the name of the process that is the parent of the session leader. For processes started within a terminal emulator, that would generally be the process running that terminal emulator (unless things like screen, expect, tmux... are being used (though note that screen and tmux are terminal emulators), or new sessions are started explicitly with setsid, start-stop-daemon...)

If you find nested parenthesis hard to read, you could write it on several lines:

ps -o comm= -p "$((
                  $(
                    ps -o ppid= -p "$((
                                      $(
                                        ps -o sid= -p "$$"
                                      )
                                    ))"
                  )
                ))"

Or use variables (which can also help make the script more self explanatory):

sid=$(ps -o sid= -p "$$")
sid_as_integer=$((sid)) # strips blanks if any
session_leader_parent=$(ps -o ppid= -p "$sid_as_integer")
session_leader_parent_as_integer=$((session_leader_parent))
emulator=$(ps -o comm= -p "$session_leader_parent_as_integer")

You could also try parsing wtmp where terminal emulators usually log an entry with their pid associated with the pseudo-terminal device. This works for me on a Debian system provided expect/screen/tmux... are not involved:

ps -o comm= -p "$(
  dump-utmp -r /var/log/wtmp |
  awk -v tty="$(ps -o tty= -p "$$")" -F ' *\\| *' '
    $2 == tty {print $5;exit}')"

(using dump-utmp from GNU acct).