Bash – Write bash_history to a file with a timestamp

bashcommand historyshell-script

The requirement is to capture command line history in a file with specific date and time of commands, when they were executed.

The below script captures history with date and time but it also assigns the current date and time for older commands. Also I want to extend the script to take incremental backup of the history output file.

#!/bin/bash
. ~/.bash_profile
HISTFILE=~/.bash_history
set -o history
history >/home/user/hist_`date "+%d%b%y%T"`

Best Answer

Not quite what you wanted, but you can get bash to add timestamps to each line in the history automatically. Simply set, for your example:

HISTTIMEFORMAT="%d%b%y%T "

The history command with no arguments will then show your history entries like this:

23Jul1515:48:14 ls -ld .

The history -w command however always writes the history file in the internal format of:

#1437659315
ls -ld .

i.e. on 2 lines, the first line holds the time in seconds "since the epoch" (i.e. 1 jan 1970) with a # in front so that it will not be confused with a command.

Related Question