Can I have a shell alias evaluate a history substitution command?

Posted by Brandon on Stack Overflow See other posts from Stack Overflow or by Brandon
Published on 2010-04-09T16:16:46Z Indexed on 2010/04/09 16:43 UTC
Read the original article Hit count: 384

Filed under:
|
|
|
|

I'm trying to write an alias for cd !!:1, which takes the 2nd word of the previous command, and changes to the directory of that name. For instance, if I type

rails new_project  
cd !!:1  

the second line will cd into the "new_project" directory.

Since !!:1 is awkward to type (even though it's short, it requires three SHIFTed keys, on opposite sides of of the keyboard, and then an unSHIFTed version of the key that was typed twice SHIFTed), I want to just type something like

cd-  

but since the !!:1 is evaluated on the command line, I (OBVIOUSLY) can't just do

alias cd-=!!:1  

or I'd be saving an alias that contained "new_project" hard-coded into it. So I tried

alias cd-='!!:1'  

The problem with this is that the !!:1 is NEVER evaluated, and I get a message that no directory named !!:1 exists. How can I make an alias where the history substitution is evaluated AT THE TIME I ISSUE THE ALIAS COMMAND, not when I define the alias, and not never?

(I've tried this in both bash and zsh, and get the same results in both.)

© Stack Overflow or respective owner

Related posts about bash

Related posts about zsh