Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent accidental history editing in bash

I recently switched from tcsh to bash, and one thing that keeps tripping me up is how bash handles history. I regularly bring up a previous history command and begin to edit it, but realize I need to run a different command first. In bash, this edits the original command, and I cannot see what I originally typed. In tcsh, the edited command is at the bottom of the stack when I use the up and down arrows, and is ready to continue editing or run when I am ready for it.

I found this question, which had several answers helpful in understanding how bash works in regards to rerunning and editing history, but I still don't know of a way to change this behavior (if such a thing exists). Is it possible to prevent bash from editing the commands that have already been run?

For example, if I run

  abcd
  efgh
  ijkl

And then use arrow up and backspace efgh to efg, then hit down and type a different command "mnop", I want my history to look like:

  abcd
  efgh
  ijkl
  mnop

Currently it looks like:

  abcd
* efg
  ijkl
  mnop

This may seem like a trivial issue but when running long commands with multiple pipes that require trial and error, it is some substantial loss of work.

like image 892
cookem Avatar asked Sep 01 '25 20:09

cookem


2 Answers

Each line maintains its own undo list which you can access with C-x C-u or C-_ to undo the most recent change, or M-r to revert all changes since it was last saved.

like image 111
chepner Avatar answered Sep 03 '25 15:09

chepner


Is it possible to prevent bash from editing the commands that have already been run?

It is possible to to prevent this "feature". I found the solution via this answer over on unix.stackexchange.

To summarize, you need to enable the revert-all-at-newline readline setting which is off by default. If the setting is on then bash will revert any changes you made to your history when you execute the next command.

To enable this setting in your shell, you should add the following to your ~/.inputrc file and then restart your shell:

$include /etc/inputrc
set revert-all-at-newline on

The first line is needed because I guess that if you supply your own .inputrc file the default /etc/inputrc file is not included which is probably not what you want.

like image 29
Gray Avatar answered Sep 03 '25 13:09

Gray