views:

5822

answers:

7

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 creatin time and not at the 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.

+6  A: 

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.

Charlie Martin
+1  A: 

You actually can't do what you want with Bash aliases, since aliases are static. Instead, use the function you have created.

Look here for more information: http://www.mactips.org/archives/2008/01/01/increase-productivity-with-bash-aliases-and-functions/. (Yes I know it's mactips.org, but it's about Bash, so don't worry.)

samoz
+4  A: 

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; }; _'
Sanjaya R
+4  A: 

To quote the bash man page:

There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell function should be used (see FUNCTIONS below).

So it looks like you've answered your own question -- use a function instead of an alias

Chris Dodd
+1  A: 

This works in ksh:

$ alias -x mkcd="mkdir \$dirname; cd \$dirname;"
$ alias mkcd
mkcd='mkdir $dirname; cd $dirname;'
$ dirname=aaa 
$ pwd
/tmp   
$ mkcd
$ pwd
/tmp/aaa

The "-x" option make the alias "exported" - alias is visible in subshells.

And be aware of fact that aliases defined in a script are not visible in that script (because aliases are expanded when a script is loaded, not when a line is interpreted). This can be solved with executing another script file in same shell (using dot).

A: 

Here is the link to find more about how to pass command line arguments to a shell script

How to pass arguments to a shell script

kvmreddy
A: 

amples of unix alias command

bhagya