24

I want to see what I typed on my bash command line on a certain day a week ago. Is there a way to retrieve command line history? Something like below, perhaps?

> history --include-date | grep 2012-02-27`
1
  • 2
    if you're using zsh: history -E
    – Vahid
    Nov 6, 2018 at 16:58

2 Answers 2

36

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.

1
  • Bash doesn't log time by default. If HISTTIMEFORMAT is not set, the command is logged without its time. Feb 27 at 18:31
0

Changing the HISTTIMEFORMAT variable will help, but unfortunately only for the future. This nixCraft article explains how to set that variable permanently, but uses an ambiguous date format. For ISO 8601, use:

HISTTIMEFORMAT="%G-%m-%dT%T "

Result:

$ history
[...]
   13  2022-11-07T13:32:01 pwd
   14  2022-11-07T13:32:05 cd
   15  2022-11-07T13:32:10 ls -l

Commands which were run before HISTTIMEFORMAT was set will display a bogus time.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .