I need to write a command or sequence of commands that lists all users who logged in on a monday by using last and grep. I came up with this but it didnt work:

grep -i /var/log/wtmp | last -t 20150731


last | grep -i Mon (although the -i option shouldn't be needed if you capitalize "Mon" as I have it)

Your proposed solution has a few problems:

  • The pipe | symbol sends (pipes) the standard output of the first program (on the left) to the second program (as standard input). So what you're doing is trying to pipe the output of grep -i /var/log/wtmp to last -t 20150731. Since last outputs the login info, it needs to come first.

  • grep -i /var/log/wtmp tries to find "/var/log/wtmp" in standard input (case insensitive). It is possible to have grep search a file, but the file comes after whatever you're searching for (e.g., grep find_me in_this_file searches the file in_this_file for the string "find_me"). Since no file is specified, it looks in standard input. With last first (before the pipe), that's the output of last; but with grep first, that's whatever you type after you hit Enter to execute the command.

  • In this case, you actually need to use grep to search for "Mon", not "/var/log/wtmp". last uses "/var/log/wtmp", but all grep cares about is the output of last, not where last gets its data from.

  • last -t 20150731 would output all logins up to (but not including) July 31, 2015. (To include July 31, you'd need to specify August 1 as the date.) Only problem is that last requires hyphens in the date unless you specify the full time (including seconds). So you need hyphens in last -t 2015-07-31 but not in last -t 20150731000000 (both of which specify the same time, midnight beginning July 31, 2015). Your initial question doesn't specify a need to limit the list by date, so I've left it out of my answer above; if you do need to limit by date, use last -t 2015-07-31 to list through July 30 (not including July 31) or last -t 2015-08-01 through July 31.

For more details (including all the fun stuff grep can do with regular expressions and the different time formats for last), try checking the man pages with man grep and man last.

The above displays logins in reverse chronological order (most recent first). Although it goes beyond the constraints of your original question by adding another command, you can also display the results in chronological order (most recent last) by piping the results of grep to the tac command: last | grep -i Mon | tac.

last | grep Mon | awk '{print $1}' | sort -u
  • 2
    No point piping grep to awk: last | awk '/Mon/ {print $1}'... – jasonwryan Sep 4 '15 at 3:54

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.