Friday, March 13, 2009

last and history

In Linux, we learn different things all the time. Today, I learned the comand "last" and how to append a timestamp into the command "history".

"history" is a common command for shell that lists all the executed commands until given the -c switch. It is very useful repeating commands that had already been executed, and investigating what commands were executed.

"last" shows a listing of last logged in users. The command searches back through the file /var/log/wtmp (or from a file designated by the -f flag) and displays a list of all users logged in (and out) since the file was created. The pseudo user reboot logs in each time the system is rebooted. Thus, the last reboot will show a log of all reboots since the log file was created. Since it would search /var/log/wtmp, a user needs to su or sudo "last".

$ sudo last
...
archie :0 Thu Mar 12 07:16 - 10:30 (03:14)
reboot system boot 2.6.27.13.tex1 Thu Mar 12 07:15 (03:15)
archie :0 Wed Mar 11 17:27 - 04:59 (11:31)
archie :0 Wed Mar 11 10:02 - 17:27 (07:24)
reboot system boot 2.6.27.13.tex1 Wed Mar 11 09:58 (19:00)
archie :0 Wed Mar 11 06:06 - 07:36 (01:29)
reboot system boot 2.6.27.13.tex1 Wed Mar 11 06:04 (01:31)
...
archie :0 Sun Mar 1 11:46 - 13:25 (01:39)
reboot system boot 2.6.27.13.tex1 Sun Mar 1 11:45 (01:40)

wtmp begins Sun Mar 1 09:26:07 2009

$ history
1 man last
2 sudo last
3 history
4 man strftime
5 history


By defalt, "history" does not append a timestamp to the list of executed command but with setting the environment variable HISTTIMEFORMAT, a user would be able to to easily configure "history" to display the date and time. HISTTIMEFORMAT uses the format string of "strftime". Check out "man strftime" to choose your preferred string.

$ export HISTTIMEFORMAT="%F %T "


The setting is equivalent to the year-month-date format in decimal number plus the time in a 24-hour-minute-second notation. Execute the command and you can immediately see the changes

$ history
1 2009-03-13 19:55:24 man last
2 2009-03-13 19:55:44 sudo last
3 2009-03-13 19:55:53 history
4 2009-03-13 19:59:46 man strftime
5 2009-03-13 20:08:21 history


Of course, when you close the shell, the changes are not saved so if you want to make the changes, add the export into your .bash_profile as well as the /root/.bash_profile. If you don't have .bash_profile, you can append the export to .bashrc.

No comments:

Post a Comment