Skip to content

Instantly share code, notes, and snippets.

@FrankSansC
Last active July 20, 2021 06:46
Show Gist options
  • Save FrankSansC/a9c98bb6890842692b816d2bea75528d to your computer and use it in GitHub Desktop.
Save FrankSansC/a9c98bb6890842692b816d2bea75528d to your computer and use it in GitHub Desktop.

Shell environment detection

For now, those methods should work on both Bash and ZSH. I am planning on adding a compatibility matrix, but this might require shifting away from markdown. See specific-shells-notes.md .

Reminders:

[[ -z $VAR ]]: Return 0 (true) if string is nonzero
*: Any number of any character. See shell globbing

Shell

Login shell

A login shell is prefixed with -. The current shell (current running application) can be queried using $0.

  • Is login: [[ $0 == -* ]]
  • Is not login: [[ $0 != -* ]]

Interactive shell

An interactive shell has the i flag set in its options. Options can be queried using $-.

  • Is interactive: [[ $- == *i* ]]
  • Is not interactive: [[ $- != *i* ]]

Specific tty

Use XDG_VTNR, set by pam_systemd

  • On tty 1 and 2: [[ $XDG_VTNR -le 2 ]], can be extended to only tty 1 by replacing 2 with 1.

Xorg

The environment variable DISPLAY is set by Xorg.

  • In Xorg Session: [[ $DISPLAY ]]
  • Not in Xorg Session: [[ ! $DISPLAY ]]

SSH

The environment variables SSH_TTY, SSH_CLIENT and SSH_CONNECTION are only set when you are in an SSH session (at least by OpenSSH).

  • In an SSH Session: [[ $SSH_CLIENT ]]
  • Not in an SSH Session: [[ ! $SSH_CLIENT ]]

GNU Screen

$TERM is prefixed with screen by default. So xterm-256color becomes screen.xterm-256color. Shared through SSH.

$STY is set by screen. Not shared with SSH.

$TERMCAP contains the screen substring. Not shared with SSH.

  • Detected from inner SSH Session:
    • In screen: [[ $STY ]]
    • Not in screen: [[ ! $STY ]]
  • Not detected from inner SSH Session:
    • In screen: [[ $TERMCAP =~ screen ]]
    • Not in screen: [[ ! $TERMCAP =~ screen ]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment