In bash, when I go back in history, edit some command and run it, this edited command is appended to history and the original one is left intact. But every once in a while I somehow manage to affect the original command, i.e. my edit replaces the original command back in history. I can't put my finger on how this happens. Can someone explain? My goal is to avoid this, so any edit to a previous command always gets appended to history and never replaces the original.
What do
echo $HISTCONTROL
echo $HISTIGNORE
give you?
Edit:
I was able to reproduce behavior similar to what you've seen by following these steps:
At the shell prompt, enter:
echo abcd
echo efgh
Press up arrow twice, so "echo abcd" is shown
Press 1 to add that character at the end
Press escape to enter command mode
Press left arrow twice so the cursor is on the "c"
Press x to delete the "c"
Press enter
Now as you step back through history, you'll see a new entry at the end:
echo abd1
and the entry that previously had "echo abcd" will now look like this:
echo abcd1
This is one way, I'm sure there are others.
Here's my own answer, please correct or provide more details if you can.
When the "vi" option is set in bash ("set -o vi" -- "Use a vi-style command line editing interface"), there are two modes of editing a command from history.
The first mode (let's call it "basic") is when you start editing immediately using Backspace, Del and character keys.
The other mode is the "vi mode", entered when you hit Esc.
If you want to keep your history intact, DO NOT use both modes in the same edit. I don't know how bash works exactly, but you can think of it this way:
- Entering the "vi mode" applies any changes done in "basic mode" to the original command, and creates a copy of the command that you can edit further using vi-style commands.
- The changes get applied when you hit Enter (execute), Up, Down or j,k (move to another command in history).
- The changes do not get applied if you hit Ctrl-C.
- Using either basic or vi-style editing ALONE does not affect the original command in history.
If you go back to some previous command and edit it, but then DON'T execute it (instead using history commands to go to some other command and execute it), then the edits will remain there in your history list