2

I'm using a bash shell. Normally if I want to repeat the last command that begins with a certain string, I can run

$ !cat

What if I want to run the last command that contains a string? That is, if I typed a command

$ cat dave.txt

and I want to run the last command with "dave" taht happened to be the above, is there a shortcut that will allow this?

Dave
  • 2,348
  • 21
  • 54
  • 84

1 Answers1

4

Use the ? event designator:

!?dave

See man bash:

?string[?]

Refer to the most recent command preceding the current position in the history list containing string. The trailing ? may be omitted if string is followed immediately by a newline.

But I find it dangerous to call a random command from the history - what if I'm in a different terminal/directory and I accidentally delete something? Ctrl + R is safer and more flexible.

choroba
  • 45,735
  • 7
  • 84
  • 110
  • 1
    A compromise is ``!?dave?:p``.  That searches history for the most recent command that contains `dave` and *displays it for you.*  Then you can pull it up again with (cursor up) or `!!` and modify it before you execute it. – G-Man Says 'Reinstate Monica' Dec 17 '20 at 08:02