There are several ways to manipulate history in zsh. One way is to use csh-style ! history:
% /usr/local/bin/!:0 !-2*:s/foo/bar/ >>!$
If you don’t want to use this, you can turn it off by typing setopt nobanghist. If you are afraid of accidentally executing the wrong command you can set the HISTVERIFY option. If this option is set, commands that result from history expansion will not be executed immediately, but will be put back into the editor buffer for further consideration.
If you’re not familiar with ! history, here follows some explanation. History substitutions always start with a !, commonly called “bang”. After the ! comes an (optional) designation of which “event” (command) to use, then a colon, and then a designation of what word of that command to use. For example, !-n refers to the command n commands ago.
% ls foo bar % cd foo % !-2 ls baz bam
No word designator was used, which means that the whole command referred to was repeated. Note that the shell will echo the result of the history substitution. The word designator can, among other things, be a number indicating the argument to use, where 0 is the command.
% /usr/bin/ls foo foo % !:0 bar /usr/bin/ls bar bar
In this example, no event designator was used, which tells zsh to use the previous command. A $ specifies the last argument
% mkdir /usr/local/lib/emacs/site-lisp/calc % cd !:$ cd /usr/local/lib/emacs/site-lisp/calc
If you use more words of the same command, only the first ! needs an event designator.
% make prig >> make.log make: *** No rule to make target ‘prig’. Stop. % cd src % !-2:0 prog >> !:$ make prog >> make.log
This is different from csh, where a bang with no event designator always refers to the previous command. If you actually like this behaviour, set the CSHJUNKIEHISTORY option.
% setopt cshjunkiehistory % !-2:0 prog2 >> !:$ make prog2 >> cshjunkiehistory
Another way to use history is to use the fc command. For example, if you type an erroneous command:
% for i in ‘cat /etc/clients‘ do rpu $i done zsh: command not found: rpu zsh: command not found: rpu zsh: command not found: rpu ...
typing fc will execute an editor on this command, allowing you to fix it. (The default editor is vi, by the way, not ed).
% fc
49
/rpu/s//rup/p
rup $i
w
49
q
for i in ‘cat /etc/clients‘
do
rup $i
done
beam up 2 days, 10:17, load average: 0.86, 0.80, 0.50
bow up 4 days, 8:41, load average: 0.91, 0.80, 0.50
burn up 17:18, load average: 0.91, 0.80, 0.50
burst up 9 days, 1:49, load average: 0.95, 0.80, 0.50
tan up 11:14, load average: 0.91, 0.80, 0.50
bathe up 3 days, 17:49, load average: 1.84, 1.79, 1.50
bird up 1 day, 9:13, load average: 1.95, 1.82, 1.51
bonnet up 2 days, 21:18, load average: 0.93, 0.80, 0.50
...
A variant of the fc command is r, which redoes the last command, with optional changes:
% echo foo foo % r echo foo foo % echo foo foo % r foo=bar echo bar bar