Add Timestamps to History File

If you’ve been using the linux command line for you may have come across the history command, which displays your shell history, or the commands you have run recently. When you run a command in the terminal, a copy of this command is saved to the .bash_history file in your home directory. You can call up and review your previous commands simply by typing history.

There are a number of handy things you can do with the history file, including:

!! rerun the last command
sudo !! rerun the last command with sudo
Very useful if you ran an admin command but forgot to use sudo. This saves you having to type the whole thing out again
!20 rerun command number 20 from the history file
!text rerun the most recent command which started with ‘text’
history -c clear the history file
history -d 20 delete entry number 20
unset $HISTFILE disable command logging

While you can disable command logging when logged in, it will be re-enabled once you log out and back in again. If you want to permanently turn off logging, add ‘unset $HISTFILE’ to your .bashrc file

By default 1,000 lines of history are saved in the history file. This is also specified in the .bashrc file, and can be changed there if you want to retain more/less logs:

Adding Timestamps

One thing you will notice though is that the history file does not tell you when a command was run. You can easily add this by adding the line below to the .bashrc file:

%F equates to full date format (YYYY-mm-dd) and %T expands to show full format (hh:mm:ss). The formats are exactly similar to those used for the date command, and you can come up with your own timestamp format using the formats listed in the date man pages (man date):

$A  Full weekday name, e.g. Sunday
%B  Full month name, e.g. January
$d  day of month, e.g. 01
%y  last two digits of year, e.g. 19

Leave a comment