2

If you do the following in Bash--maybe in other shells as well--you execute a command from your history that matches the provided keyword:

$ !keyword

I am looking for documentation for this command. I've tried searching through man bash page but no luck. I also tried Google but it's almost impossible (right?) to search for punctuation in Google.

I want to know:

  1. What order does this command search your history? Oldest command to most recent? Or other way around?

  2. I am aware of adding the :p option at the end of the command to prevent execution but is there other options? Although not sure what other options I'd want but just curious.

Of course I could figure this out by trial and error but I rather look trough the documentation before I use this neat command.

Perhaps I am looking in the wrong place? Any help in tracking down the documentation would be greatly appreciated.

2 Answers 2

2

This is called history expansion. Most history expansion commands refer to the most recent matching command line (the exceptions are references to a command line by number).

The most useful forms are !prefix expanding to the most recent command beginning with prefix, !?substring? expanding to the most recent command containing substring, and ^from^to which replaces from by to in the previous command.

You can extract only a specific word instead of the whole line by adding a word designator, as in

ls foo bar *~ *.pdf
rm !*

Modifiers can performs string substitutions and extract parts of words. The modifier :p causes the resulting command to be printed but not executed.

0

The order is most recent to oldest.

!n executes the command with the number n in history.

!-n executes the nth last command in the history.

!! executes the last command (i.e. !-1).

You can also e.g. sudo !! if you forgot to prefix something with sudo.

You can google for bang or bang bang to find something on these commands, such as this or this

Also:

Most modern shells support csh's bang commands - bash, tcsh and zsh all do. While some bang commands don't work in all those shells, all of the following do

So you might be better off looking in the csh documentation.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .