In bash, there is an option that instructs bash to record a timestamp with each command. You do this by assigning a useful value to the environment variable HISTTIMEFORMAT
. From the bash
manpage:
If this variable is set and not null, its value is used as a
format string for strftime(3)
to print the time stamp associated
with each history entry displayed by the history builtin. If
this variable is set, time stamps are written to the history
file so they may be preserved across shell sessions. This uses
the history comment character to distinguish timestamps from
other history lines.
Note, after having activated HISTTIMEFORMAT
then ~/.bash_history
will have always two lines per each recorded command:
In my environment, I use
HISTTIMEFORMAT="%s (%H:%M:%S):"
When you invoke history
that tool formats the timestamp on the fly with your defined format. I use above formatting so that commands may be sorted easily (%s
is timestamp in seconds) and human-readable. In my shell, when I type history
, I see something like the following:
3 1437664568 (17:16:08):man bash
4 1437664699 (17:18:19):history
Note: All commands prior your activation of timestamp recording, are only the command without the prefixed timestamp line. Hence they show the date/timestamp when you logged into your current session. If that annoys you, then simply do a find/replace of your legacy lines to prefix them with an artificial timestamp. And add a note on the boundary line for documentation purposes. Like this:
#1671058800
ls -l
#1671058800
exit
#1671094600
echo Activated timestamp recording in the history file now.
#1671094610
echo All commands prior got the artificial timestamp 2022-12-15 00:00:00 (1671058800).
#1671094622
cd /
#1671094627
exit
EDIT: OPs question not fully answered.
Also I want to extend the script to take incremental backup of the history output file
I'm not sure what you mean by "incremental backup" of the history file. Perhaps you simply want the history backed up periodically. There are a couple of approaches you can take:
- Set PROMPT_COMMAND variable with
history -a
to continually update the history command after every invocation (as opposed to waiting for logout).
- Trap the DEBUG signal with a function you define. Every time a command is entered, the function will be called. From within the function you can do everything. (Slightly more reliable than PROMPT_COMMAND).
- cronjob to periodically copy/archive the history file.