10.6. Checking the Current TTY

The tty command returns the filename of the terminal connected to standard input. This comes in two formats on the Linux systems I have used, either "/dev/tty4" (on the console) or "/dev/pts/2" (in an X terminal). I've used several methods over time, but the simplest I've found so far is echo $(basename $(tty)). This would return "tty4" or just "2" given the previous two examples.

For reference, I'm including some of the other ways I've done this:

temp=$(tty) ; echo ${temp:5}

tty | sed -e "s:/dev/::" , which removes the leading "/dev/".

Older systems (in my experience, RedHat through 5.2) returned only filenames in the "/dev/tty4" format, so I used tty | sed -e "s/.*tty\(.*\)/\1/".

ps ax | grep $$ | awk '{ print $2 }' | uniq

Relative speed: the ${temp:5} method takes about 0.24 seconds on an unloaded 800MHz Celeron, the sed-driven method takes about 0.055 seconds, the awk-driven method takes about 0.125 seconds.