tags:

views:

125

answers:

7

I have two commands I execute frequently. Let's say the first is 'abcd' and the second is 'abc'. So my history contains

1000 abc arg1 arg2 arg3
1001 abcd arg1 arg2 arg3

Now if I type '!abcd' in bash, it executes the abcd command. which is fine. But if I type '!abc' in bash, it also executes the last abcd command (since it matches the beginning and is 'newer')

How do I use bash history to grab the last abc command? I've tried !'abc ' and "!abc\ " backslashing the space.

+4  A: 

You might try reverse history searching: Ctrl-R. On the prompt that appears, type in parts of your commandline (incremental text search).

If you want to switch to the previous match, type some more Ctrl-R.

In your "two similar lines" case,

Ctrl-R abc Ctrl-R

or

Ctrl-R abc<SPACE>

might do it

TheBonsai
+1  A: 

If you know the history number, you could just

!1000

or use

!-2

refer to the line before previous.

kcwu
I also thought about that. But it felt too static.Who knows, maybe he has a readonly history file with his standard commands :)
TheBonsai
+1  A: 

One way to do what you're asking is to use the history search features in bash. With emacs keybindings (the default) you can press CTRL-r. With vi keybindings use ESC /. This will also let you search for other parts of the command.

Laurence Gonsalves
You're right, didn't think of the different input methods (not speaking of customized bindings), ++ for that
TheBonsai
I use vi bindings in bash, so I actually had to look up the emacs-bindings equivalent. :-)
Laurence Gonsalves
+1  A: 

Try:

!?abc ?

That's a space before the second question mark. Note that this (!?) would find "abc<space>" anywhere on the command line not just at the beginning as "!" would. The second question mark means that the string may have additional text after it (your args, for example) as well as delimiting the space character.

Dennis Williamson
+1  A: 

This doesn't answer your question directly, but if you execute those commands frequently, you might consider adding an alias or function definition to the appropriate login dotfile so that you can execute them with 1-letter commands:

alias a="abc arg1 arg2 arg3"
alias b="abcd arg1 arg2 arg3"
+2  A: 

Since Bash uses readline, try adding this to ~/.inputrc and restarting Bash:

"\e[5~": history-search-backward
"\e[6~": history-search-forward

This lets you simply type

$ abc <PgUp>

to retrieve the last item in history beginning with "abc ".

There was a proposal to add these bindings to the default /etc/inputrc in some popular Linux distro... I don't remember what it was.

ephemient
+1  A: 

If you want to keep the dupes out of your history, put this in your bash startup (.bash_profile or .bashrc)

export HISTCONTROL="ignoredups"
Grant