Linuxdoc Linux Questions
Click here to ask our community of linux experts!
Custom Search

11.5. 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" or "/dev/pts/2". I've used several methods over time, but the simplest I've found so far (probably both Linux- and Bash-2.x specific) is temp=$(tty) ; echo ${temp:5}. This removes the first five characters of the tty output, in this case "/dev/".

Previously, I used 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/".

An alternative method: ps ax | grep $$ | awk '{ print $2 }'.

Relative speed: the ${temp:5} method takes about 0.12 seconds on an unloaded 486SX25, the sed-driven method takes about 0.19 seconds, the awk-driven method takes about 0.79 seconds.