How to pass command line arguments to a shell alia

2019-01-01 01:52发布

How do I pass the command line arguments to an alias? Here is a sample:

alias mkcd='mkdir $1; cd $1;'

But in this case the $xx is getting translated at the alias creating time and not at runtime. I have, however, created a workaround using a shell function (after googling a little) like below:

function mkcd(){
  mkdir $1
  cd $1
}

Just wanted to know if there is a way to make aliases that accept CL parameters.
BTW - I use 'bash' as my default shell.

标签: shell alias
12条回答
长期被迫恋爱
2楼-- · 2019-01-01 02:01

An empty alias will execute its args:

alias DEBUG=
查看更多
妖精总统
3楼-- · 2019-01-01 02:02

You found the way: create a function instead of an alias. The C shell has a mechanism for doing arguments to aliases, but bash and the Korn shell don't, because the function mechanism is more flexible and offers the same capability.

查看更多
有味是清欢
4楼-- · 2019-01-01 02:02

You cannot in ksh, but you can in csh.

alias mkcd 'mkdir \!^; cd \!^1'

In ksh, function is the way to go. But if you really really wanted to use alias:

alias mkcd='_(){ mkdir $1; cd $1; }; _'
查看更多
墨雨无痕
5楼-- · 2019-01-01 02:02

You may also find this command useful:

mkdir dirname && cd $_

where dirname is the name of the directory you want to create

查看更多
余欢
6楼-- · 2019-01-01 02:06

Just to reiterate what has been posted for other shells, in Bash the following works:

alias blah='function _blah(){ echo "First: $1"; echo "Second: $2"; };_blah'

Running the following:

blah one two

Gives the output below:

First: one
Second: two
查看更多
爱死公子算了
7楼-- · 2019-01-01 02:08

The easiest way, is to use function not alias. you can still call a function at any time from the cli. In bash, you can just add function name() { command } it loads the same as an alias.

function mkcd() { mkdir $1; cd $1 ;}

Not sure about other shells

查看更多
登录 后发表回答