There are times when you want to do the same thing over, maybe with just a small change. Easy, peasy: if it's the most recent command, hit the up arrow, then edit the line to our heart's content.
Reverse Search
And if the command we want to edit isn't the most recent? Use bash's reverse incremental search. Control-r (hereafter ^ for control, so ^r), start typing until you get the line you want, then edit away. R, by the way, for "reverse" search.
It helps a lot to think of bash's history as a "file" you search in and edit with some Emacs commands (or vi commands, if you've set that up).
fc
Bash has a line editor built in, called "fc". As usual, the gory details are available in "man bash", and probably in "info bash" if you have the bash docs loaded.
To use fc, you call `fc' with appropriate options.
Listing Previous Commands
You can see the last ten commands you executed with
fc -l -10
Note that minus sign! Remember what I said about thinking of your bash history as a file.
Executing Previous Commands
Say we're working in a git repo and we recently looked at the git log. So in our recent history we have:
$ fc -l -10
2065 git st
2066 git commit -a
2067 git log
2068 rm content/*.md~
2069 ll content/
2070 git st
2071 git diff
2072 git commit -a
2073 git st
2074 pelican
Let's run that git log
command again:
fc -s 2067
Editing and Executing
Let's take another look at git's log, this time for the file README. This time we edit the line before bash executes it for us.
fc -s log='log README' 2067
Note the single quotes to handle that space between the second log
and README
.
We specified the line number of the command to edit and execute. If you omit the line number, you edit and execute the most recent command.
fc replaces multiple instances of a search string with its replacement. For example, having hauled in a monster iso file, and two checksum files for it:
$ sha256sum --q -c honking.big.iso.sha256sums
$ fc -s 256=512
sha512sum --q -c honking.big.iso.sha512sums
$
Using an external editor
You can select and use an external editor. If the variable FCEDIT is set, fc will use that. Otherwise, it will use the variable EDITOR. Failing those two, fc will use vi. So we can do:
$ export FCEDIT=nano
$ echo 'foo'
foo
$ fc
bar
You can also select an editor as part of the fc command. So to edit the previous command with Emacs, assuming you have emacsclient set up:
fc -e emacsclient
Which means if you don't want to edit a line, just re-execute it as is, specifying -
as your editor:
fc -e - 2067