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
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.
In my environment, I use
So that the 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
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.