zsh history expansion

Exploring zsh features made me want to figure out some of the history-editing wizardry. (Bash has similar history tricks, I just never bothered to dive too deeply into them.)

If you want to experiment with history expansion a bit, you can echo the result instead of executing it:

hostname:~/dir% ls /some/long/path/to/file_0.1-2_i386.changes
hostname:~/dir% echo !?ls?:s/-2/-3/
echo ls /some/long/path/to/file_0.1-3_i386.changes

In this case, what I wanted to do is repeat a long command that referenced a file with a version number in it --- but I wanted to use a different version number (-3 instead of the previously given version -2).

History expansion uses "!" ("bang", or exclamation point). If you want to select the previous command to expand based on a string match, "!?str" will find the previous command that contains "str". If you want to substitute some part of that previous command, put another question mark on the end, add a colon, and use the the "s" modifier. In the example above, "!?ls?" means expand the previous command containing "ls". The ":s/-2/-3/" means modify that expanded command to replace the occurrence of "-2" with "-3".

(Of course, to actually get all of that figured out and working, I had to iterate the sequence of commands above about a dozen times.)

Leave a comment with your favorite zsh history trick. Thanks!

Posted on 2010-02-15 by brian in zsh .
Comments on this post are closed. If you have something to share, please send me email.