I'm writing a bash script that disconnects idle sessions but writes to the tty a few seconds before terminating it to make sure it really is not being used.

The format for write is write user [tty].

I'm starting with a tty string, i.e "pts/1".

I know I can find the user next to the tty name in "who" and "w", but am uncertain of how to put the username (i.e john) in a variable. Would this require a regex? I was originally looking for a single command but who and w don't have such options in their documentation.

  • ttys=$(who | awk '{print $2}'); echo $ttys – Cyrus Dec 14 '14 at 17:30

This should work. It uses stat to extract the username of the owner of the pseudo-tty. Here, $pts should be in the format in the question, eg. pts/2.

tty_user=$(stat -c%U /dev/$pts)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.