How to get the tty in which bash is running?
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)
If you want to be more efficient, then yes, you're right that ps
can filter to just the process in question (and it will be more correct, not running the risk of picking up commands that happen to have your process number in their names). Not only that, but it can be told not to generate the header (option h
), eliminating the tail
process, and to display only the TTY
field (option o tty
), eliminating the awk
process.
So here's your reduced command:
ps hotty $$
Other ways to do it:
readlink /dev/fd/0 #or 1 or 2
readlink /proc/self/fd/0 #or 1 or 2
readlink -f /dev/stdin #or stdout or stderr; f to resolve recursively
#etc.
(
If you're in a shell whose stdin, stdout and stderr are not connected to its controlling terminal, you can get a filedescriptor to the controlling terminal by opening /dev/tty
:
( { readlink /dev/fd/0; } </dev/tty; ) </dev/null >output 2>&1
)
Or with ps
:
ps h -o tty -p $$ #no header (h); print tty column; for pid $$