Retrieve Linux command line history by date
Solution 1:
By default, History
logs the time when you ran a command, but doesn't display it. The reason for this is when you run the History
command, it looks for an environment variable called HISTTIMEFORMAT
, which tells it how to format time. If the value is null
or not set, then by default it doesn't show any time.
An example with some time-
[qweet@superbox ~]$ export HISTTIMEFORMAT='%F %t '
[qweet@superbox ~]$ history
1 2012-03-06 su -
2 2012-03-06 [email protected]
3 2012-03-06 mysql
4 2012-03-06 ll
5 2012-03-06 cd /opt/
6 2012-03-06 ll
7 2012-03-06 exit
8 2012-03-06 ll
9 2012-03-06 ls -lsa
10 2012-03-06 cd ../
11 2012-03-06 ll
12 2012-03-06 ll
....
But that's not all. Since the HISTTIMEFORMAT
takes strftime
values (which you can find here btw), you can do all sorts of magical things. But for what you want to do, the following works.
[qweet@superbox ~]$ export HISTTIMEFORMAT='%F %T %t'
[qweet@superbox ~]$ history | grep -e "2012-03-06 14:48"
1006 2012-03-06 14:48:05 export HISTTIMEFORMAT='%F %T %t'
1007 2012-03-06 14:48:07 history
...
Also, if you want your HISTTIMEFORMAT to persist, consider appending it to your bashrc
like so;
echo 'HISTTIMEFORMAT="variables here"' >> ~/.bashrc
You will see the changes when you open a new tab in the terminal, or logging out and in.