Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 2 down vote accepted
!?foo bar


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

Better answer:

!{?foo bar?}

I find the braces helpful in delaying history expansion with magic-space, though they are documented as:

Insulate a history reference from adjacent characters (if necessary).

on the page:

Note: in some cases it may be much faster to use the nth previous history item syntax like:


for 2nd command back, !-1 is the same as !!

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.