History comment character

Viewed 151

Whilst tinkering with history settings, I keep seeing references to the 'history comment character' in the man pages. Is this different to using # for commenting in Bash?

I can't seem to find an answer as to what actual character code is for the history comment character and how it differs to a conventional bash comment?

1 Answers

This is how I understand it:

There is the "normal" comment character, #, which can't be changed. It indicates the start of a comment in scripts and in interactive sessions (unless the interactive_comments shell option is disabled), and everything from that character on is ignored.

The history comment character can be set using histchars; the default value is !^#.

  • ! is used to indicate history expansion (like "repeat previous command": !!)

  • ^ is to substitute something in the previous command:

    $ echo foo foo
    foo foo
    $ ^foo^bar^     # final ^ is optional
    bar foo
    
    
  • # is the history comment character.

The history comment character is used:

  • In ~/.bash_history, to mark timestamps as comments when HISTTIMEFORMAT is set:

    #1597532894
    echo foo
    #1597532908
    histchars='!^@'
    @1597532918
    vim ~/.bash_history
    

    Notice how the timestamp prefix switches to @ after the second command.

  • To skip history substitution for the remaining words on a line:

    $ echo foo
    foo
    $ echo !$ @ !$ # !$
    foo @ foo
    $ histchars='!^@'
    $ echo foo
    foo
    $ echo !$ @ !$ # !$
    foo @ !$
    

    !$ is "the last word of the previous command". With the default settings (history comment character is #), echo !$ @ !$ # !$ expands to echo foo @ foo # !$ and prints foo @ foo; everything after # is ignored. When switching the history comment character to @, the second !$ is not expanded to foo any longer.

When would you use that? I honestly don't know, and it really only applies to interactive shell sessions, where the default of # make total sense, and anything else would be highly surprising behaviour to me. I can't find anything in the Bash release notes to explain what the intended purpose of being able to separately set the history comment character is.

Related