Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.)

like image 799
iconoclast Avatar asked Apr 09 '10 16:04

iconoclast


People also ask

Can a bash alias take argument?

Bash users need to understand that alias cannot take arguments and parameters. But we can use functions to take arguments and parameters while using alias commands.

What does the shell function alias do?

A shell alias is a shortcut to reference a command. It can be used to avoid typing long commands or as a means to correct incorrect input. For common patterns it can reduce keystrokes and improve efficiency. A simple example is setting default options on commands to avoid having to type them each time a command is run.

Can you use alias in shell script?

An alias is a way of shortening a command. (They are only used in interactive shells and not in scripts — this is one of the very few differences between a script and an interactive shell.)

Does Korn shell support aliases?

The Korn shell, or POSIX shell, allows you to create aliases to customize commands. The alias command defines a word of the form Name=String as an alias. When you use an alias as the first word of a command line, ksh checks to see if it is already processing an alias with the same name.


2 Answers

For bash:

alias cd-='cd $(history -p !!:1)'
like image 54
Teddy Avatar answered Oct 11 '22 20:10

Teddy


Another way to accomplish the same thing:

For the last argument:

cd Alt-.

or

cd Esc .

For the first argument:

cd Alt-Ctrl-y

or

cd Esc Ctrl-y

like image 40
Dennis Williamson Avatar answered Oct 11 '22 19:10

Dennis Williamson