Bash – How to get the tty in which bash is running

bashpstty

In the second method proposed by this page, one gets the tty in which bash is being run with the command:

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

I though to myself that surely this is a bit lazy, listing all running processes only to extract one of them. Would it not be more efficient (I am also asking if this would introduce unwanted effects) to do:

ps -p $$ | tail -n 1 | awk '{ print $2 }'

FYI, I came across this issue because sometimes the first command would actually yield two (or more) lines. This would happen randomly, when there would be another process running with a PID that contains $$ as a substring. In the second approach, I am avoiding such cases by requesting the PID that I know I want.

Best Answer

Simply by typing tty:

$ tty 
/dev/pts/20

Too simple and obvious to be true :)

Edit: The first one returns you also the pty of the process running grep as you can notice:

$ ps ax | grep $$
28295 pts/20   Ss     0:00 /bin/bash
29786 pts/20   S+     0:00 grep --color=auto 28295

therefore you would need to filter out the grep to get only one result, which is getting ugly:

ps ax | grep $$ | grep -v grep | awk '{ print $2 }'

or using

ps ax | grep "^$$" | awk '{ print $2 }'

(a more sane variant)

Related Question