Take the 2-minute tour ×

I want to repeat the last command that matches foo bar. Using !! doesn't work (it's not the last command I used), and neither does !foo, because my history looks something like

foo bar dee zep
foo boo lee kee
foo bee

If I try to type !foo bar, zsh auto-completes to foo bee (which is the same as !! anyway) as I hit the space. How would I do this?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted
!?foo bar

See http://zsh.sourceforge.net/Doc/Release/Expansion.html#Event-Designators

Edit: No, you must not escape the spaces. If you need to add something that is not part of the history expansion, separate it with another ?, e.g.:

echo hello
echo foo
!?echo hello? world # runs "echo hello world"
share|improve this answer
do you need to escape the spaces? –  rubixibuc Feb 19 '12 at 3:30
Perhaps I'm unable to do this because I'm using oh-my-zsh; I can't type !?foo bar, because as I hit the ' ' space key, zsh autocompletes to foo bee; I lose the event designator from the prompt, and further ? don't help me replace bee with bar. –  simont Feb 29 '12 at 19:22
There's an bindkey in oh-my-zsh, under lib/keybindings.zsh, called magic-space (line 23, approx). It does history expansion on ' '; disabling this bind allowed me to use the !? event designator. Thanks :) –  simont Apr 13 '12 at 21:32
add comment

Your Answer


