2

I use a coloured bash prompt like so:

blue=$(tput setaf 4)
reset=$(tput sgr0)
bold=$(tput bold)
export PS1='($?) \[$bold$blue\]\u@\h:\w\[$reset\]$(__git_ps1)> '

I usually work in a terminal window (gnome-terminal) but sometimes in a full-screen console (CTRL+ALT+F3).

My coloured prompt is fine in the GUI terminal but hard to read in full-screen because the colours look different. So I'd like to use a different colour (e.g. cyan=$(tput setaf 6)), when in console window. For this to work I need to figure out which mode I'm currently in and set my $PS1 accordingly.

I tried the tty command. It gives

/dev/pts/0  # GUI terminal
/dev/tty3   # console 

I also tried to examine the value of $TERM. It gives

xterm-256color  # GUI terminal
linux           # console

Both of them would work for me but my question is: Is that the correct way to reliably distinguish console vs. terminal or are there better ways? I'm on 17.10.1 if that matters.

  • "Correct" depends on what the most important characteristic is. It appears that it is "is this Linux virtual terminal or not", and then $TERM is fine. – Thorbjørn Ravn Andersen Mar 1 '18 at 0:34
5

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:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.