tags:

views:

230

answers:

3

I know about the bash history navigation with the Up and Down arrows.

I would like a lazy way to select a previous command that matches some regex (that is shorter than the whole command, so it takes less time to be typed).

Is it possible with bash?

If not, do other shells have such a feature?

+2  A: 

You can always use CTRL-R to search your history backward, and type some part of the previous command. Hitting CTRL-R again (after the first hit) repeats your query (jumps to the next match if any).

Personally I use this for regex search (as regex searching is not possible yet (AFAIK)):

# search (using perl regexp syntax) your entire history
function histgrep()
{
     grep -P $@ ~/.bash_history
}

Edit: For searching most recent history items via that function, see this (on setting $PROMPT_COMMAND ).

Zsolt Botykai
I might be wrong about this, but I used to think that the history file gets written when the user logs off, so if this is true, then this file does not contain recent commands. CTRL-R seems to do the trick, thanks.
Anonymous
See this for updating your history file automatically after every command: http://briancarper.net/blog/keeping-bash-history-in-sync-on-disk-and-between-multiple-terminals HTH
Zsolt Botykai
+4  A: 

Zsolt, avoid hard-coded filenames, use the HISTFILE variable instead, with a fallback if you're really paranoid: ${HISTFILE:-~/.bash_history} ;-)

Any why grepping directly through the history file?! You'd lose the history number, which is necessary to replicate the command (e.g. !33 to execute again the 33th entry from your history) without having to copy&paste grep's output.

Please keep in mind that using that kind of $@ expansions may fail at various (epic) levels. For instance, an argument beginning with "-" (histgrep -h) will usually hang, or shoot yourself in the foot. Indeed, this basic example may be worked around easily, following the classic "--" way of separating arguments from options, but the discussion has no ending, remembering that the arguments to be provided to that hack would be regular expressions. ;-)

Oh, and isn't histgrep somehow a too verbose choice? h, i, Tab, g, Tab :)

IMHO I'd stick to using ^R, falling back to history | grep ... whenever necessary. Anyway, for the sake of the example, I'd (lazily) rewrite this little helper as:

function hgrep() { history | grep -P -- "$*"; }
altblue
Thanks for the adv ice!(+1)
Zsolt Botykai
A: 

See my answer here

Example:

$echo happy
happy
$!?pp?
happy
Dennis Williamson