Does bash (or any shell, for that matter) have an 'overwrite' mode?

I'm running similar commands on (e.g.) a set of files. As an example, let's say I'm doing something like this (this isn't what I'm doing, it's just an example):

> cat path/to/dir/file01.txt
  [file contents]
> another-command path/to/dir/file01.txt
  [more output]
> cat path2/to/dir/file02.txt
  [file contents, from which I can tell I should do something different]
> different-command path2/to/dir/file02.txt
  [yet more output]
> cat path3/to/dir/file03.txt
  [file contents]
> another-command path3/to/dir/file03.txt
  [output]

etc.

It would be convenient if, after using the key to return to a previous command, I could overwrite non-duplicated text ― like the file name, or a common part of the path — rather than having to delete it and retype it.

Is there a way to do this?


Not what you asked for directly, but you can use various forms of history interaction to simplify your task:

$ cat path/to/dir/file01.txt
cat: path/to/dir/file01.txt: No such file or directory
$ different-command !$
different-command path/to/dir/file01.txt
bash: different-command: command not found
$ cat !$:s/1/2/
cat path/to/dir/file02.txt
cat: path/to/dir/file02.txt: No such file or directory
$ ^2^3
cat path/to/dir/file03.txt
cat: path/to/dir/file03.txt: No such file or directory
$ !-3:s/1/3/
different-command path/to/dir/file03.txt
bash: different-command: command not found
$ !diff:s/3/4/
different-command path/to/dir/file04.txt
bash: different-command: command not found

Ignoring the errors, each time I used history interaction (!$, !$:s/1/2, ^2^3), you can see how bash expanded it.

  • !$ - the last word of the previous command
  • :s/1/2 - replace the first occurrence of 1 with 2 in the selected word (in this case, that was !$ again).
  • ^2^3 - replace the first occurrence of 2 with 3 in the entire previous command.
  • !-3 - run the third-last command.
  • !diff - run the last command that started with diff.

You can bind a key to a readline directive in $HOME/.inputrc.

"code": overwrite-mode

To discover the code generated by a specific key press CtrlandV together then hit that key. For example when you hit the Ins (insert) key you see ^[[2~. Beware that ^[ is just the screen representation for ESC, which is represented with \e for readline. Therefore you should add the following line to $HOME/.inputrc:

"\e[2~": overwrite-mode

and restart bash.