Single Line Version
Here is the single line version. This is the original. I also published a short version of the function and a long version of the function with a few added functions. I like versions of functions because they will not absorb other variables in your environment, and they are much more readable than single-line ones. This post has some information on how they all work, which may not be duplicated in others.
Add the following to your ~/.bashrc :
export PROMPT_COMMAND='hpwd=$(history 1); hpwd="${hpwd# *[0-9]* }"; if [[ ${hpwd%% *} == "cd" ]]; then cwd=$OLDPWD; else cwd=$PWD; fi; hpwd="${hpwd% ### *} ### $cwd"; history -s "$hpwd"'
This makes a history entry that looks like this:
rm subdir/file
I use ### as a comment separator to separate it from comments that the user can enter, and to reduce the likelihood of collisions when deleting old comments to paths that would otherwise accumulate when the enter key was pressed on an empty command line. Unfortunately, a side effect is that a command like echo " ### " distorted, although this should be pretty rare.
Some people find it unpleasant that I reuse the same variable name. Normally, I would not, but here I try to minimize the footprint. It has easily changed anyway.
This blindly assumes that you are not using HISTTIMEFORMAT or are modifying the story in any other way. It would be easy to add the date command to the comment instead of the HISTTIMEFORMAT function. However, if you need to use it for some reason, it still works in a subshell, as it automatically shuts down:
$ htf="%Y-%m-%d %R "
There are a couple of very small problems with this. One of them is if you use the history command, for example, like this:
$ history 3 echo "hello world"
The result will not display a comment on the history command itself, even if you see it if you press the up arrow or enter another history command.
Another is that commands with inline newlines leave an uncommented copy in the history in addition to the commented out copy.
There may be other problems that are being discovered. Let me know if you find.
How does it work
Bash executes the command contained in the PROMPT_COMMAND variable each time a PS1 primary prompt is issued. This little script uses this feature to grab the last command in history, add a comment, and save it back.
Here it is shared with comments:
hpwd=$(history 1)