GNU/Linux alias with arguments

Written on July 2, 2014

I used to create (GNU/Linux) alias as way to rename the standard commands, like this:

alias rm='rm -rf'

But since I started the PhD, each time I use more sophisticated commands and today I want to create an alias that accepts arguments. Let see, I want a command to obtain the result of running:

ls -a | nl

Thit was perfect to see the numbered files in the actual path.

alias lsn='ls -a | nl'

But when doing that:

lsn /tmp/

I got an unexpected error:

nl: /tmp: Is a directory

And that because the argument /tmp is given to the second particle of the pipe, to the nl and not to the ls -a. It is know that alias doses not accept arguments (correct me if Iā€™m wrong). So the solution to that is to use bash function and assign the function to the alias.

First we can create the function that accepts the argument and runs the desired command:

lsn_fun() {
ls -a $1 | nl
}

And we assign the function to the alias:

alias lsn=lsn_fun

So now we can run the alias using arguments:

lsn /tmp

1 .
2 ..
3 12904-rsession
4 13126-rsession