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
:Too simple and obvious to be true :)
Edit: The first one returns you also the
pty
of the process runninggrep
as you can notice:therefore you would need to filter out the grep to get only one result, which is getting ugly:
or using
(a more sane variant)