How can I add a command to the Bash history without executing it?

Every now and then it would be useful to add a command directly to the history in Bash without actually executing it. So far the closed thing I have found is adding a # in front of it and hitting return. Are there better ways?


Solution 1:

history -s command

Solution 2:

history -s command

You can even bind a keystroke to do this for you. You can enter this at a Bash prompt:

bind '"\C-q": "\C-a history -s \C-j"'

or add this to your ~/.inputrc:

"\C-q": "\C-a history -s \C-j"

then you can type something and press Ctrl-q and it will be added to the history without being executed. The space before "history" causes the history command itself to not be added to the history if your HISTCONTROL variable contains ignorespace or ignoreboth. Another keystroke could be chosen instead of "\C-q".