Like the following answer Bash command to determine first login for a particular time period, instead of for a duration I want to find out to check is the first time the user connected into machine using ssh.

Is it possible to find out it a specific user?


This line should print "First" if it's the first login by user "user" since reboot from non-local host:

[ $( last | sed '/^reboot/,$d' | egrep '^user +pts/' | wc -l ) -lt 2 ] && echo First

Note that the last log is usually rotated monthly, so the answer might be incorrect if the user has logged in more than one month ago. I anchor the expression with ^ to make sure the user name is picked from the first column (should the user's name be still, we'd get a false hit on lines reading still logged in :-) and I also expect pts/ to appear, indicating a remote login (local logins are indicated with tty instead).

This should work even if the computer hasn't been rebooted current month. But it would not work if your user's login name is verbatim reboot.

| improve this answer | |
  • If I understand correctly, right after reboot when I run your script it shouldn't print First. So that way I can under stand that the user logged in using ssh first time. But it always print First – alper Jun 29 at 19:19
  • 1
    Notice that I assume you replace user above with the login name of the user you wish to check. If you want a more generic solution replace user with either '$(whoami)' or '$LOGNAME' including the apostrophes. If you still feel it doesn't work, could you please provide the output from your last command (replace real names with fake names for security reasons but be consequent). – Rein Jul 1 at 18:15
  • People who read this site expect questions to lead to a full and verified answer, not a long debate. Usually these comments are requests for more information, which is expected to be provided. I asked you to provide output, so I could verify my answer, and then add it as an answer for others having the same question. Instead you write "this also works". If you want, you can answer your own question, which can give you credits. I'm out! – Rein Jul 6 at 9:00
  • I wasn't meant to debate the answer. I appreciate your valuable answer and your time to answered it. // I added '$(whoami)' but forget to include apostrophes so I keep getting First, than using [[:space:]] helped, but there was no need for that, adding apostrophes was enough. @Rein – alper Jul 6 at 9:22

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.