How can I distinguish a terminal window (GUI) from a console (CTRL+ALT+F3)?

Solution 1:

There are a number of ways to determine that, three famous being:

  • tty - print the file name of the terminal connected to standard input:

    /dev/pts/10
    /dev/tty1
    

    This function written by Sergiy Kolodyazhnyy makes use of tty.

  • ps hotty $$ (short for ps --no-header --format tty --pid $$):

    pts/10
    tty1
    
  • who who whom | awk '{ print $2 }' (in fact that's who with two arbitrary arguments, equal to who -m – which also matches the pun):

    pts/10
    tty1
    

I suspect the values of TERM to differ between distributions and even releases, but tty is a stable and reliable way. I would use it like so:

if tty|grep -q tty; then
  echo "That's a TTY."
else
  echo "That's not a TTY."
fi

There seems to be a problem with at least who in gnome-terminal, luckily there's a wrapper script to work around this issue.

Helpful links:

  • How to check which tty am I using
  • How to get the tty in which bash is running? · Unix.SE
  • Bash Prompt HOWTO: Checking the Current TTY