Bash – Programmatically Add Entries to Bash History with Proper Timestamps

bashcommand history

On CentOS 6.2 and Bash 4.1.2(1), I have added a file in /etc/profile.d which contains:

HISTTIMEFORMAT='%c : '
history -s "# some text as a marker"

That works insofar as the the variable gets set and the marker is written to the user's history list (and to ~/.bash_history when they exit).

The problems are:

  • history -s doesn't add a timestamp when it adds the marker
  • scrolling back through history stops at the marker (the ~/.bash_history file isn't read into memory)
  • the history entry for the marker comment has "??" instead of the (missing) timestamp

I tried adding:

history -s "#$(date +%s)"

before the other history -s command, but Bash sees this as a command in history rather than a timestamp even though it's in the same format.

Another option is to append the marker and a timestamp directly to ~/.bash_history, but then they are not contiguous with the activity in the session's history when it later gets appended. There may be other sessions that get appended between the marker and its related session due to other users or multiple sessions by a single user.

Is there any way to solve these problems?

Update:

I have tried adding set -o history (and removed the history -s "#$(date +%s)" line) and it seems to solve the history scrolling problem mentioned above, but the lack of timestamp is still a problem.

Best Answer

I posted this question on the help-bash mailing list and got a response from Chet Ramey, the maintainer of Bash.

He suggested adding either of the following before the history -s command:

set -H    # aka set -o histexpand

or

histchars='!^#'

I tried each of them and they both work. The reason is that the history comment character which defaults to # hasn't been set at the point that the profile code is running and so is null (\0).

Here's my working file:

HISTTIMEFORMAT='%c : '
histchars='!^#'
set -o history
history -s "# some text as a marker"
Related Question