Can I pass arguments to an alias command?

I want to know if I can pass an argument with an alias command.

for example:

alias d="dmesg | grep -iw usb | tail -5" 

Now d will print the last 5 lines. If I want to use d to print a different number of lines, I have to make change in the alias command declaration of d again.

Is there any way I can modify the declaration of an alias so that I don't have to retype the declaration to change the number of lines. Like incorporating passing the number of lines as an argument while declaring alias for d? Or is there some other method to solve this?


Solution 1:

Aliases don't take arguments. With an alias like alias foo='bar $1', the $1 will be expanded by the shell to the shell's first argument (which is likely nothing) when the alias is run.

So: Use functions, instead.

d () {
  num=${1:-5}
  dmesg |grep -iw usb|tail -$num
}

num=${1:-5} uses the first argument, with a default value of 5 if it isn't provided.

Then you can do:

$ d
# prints 5 lines
$ d 10
# prints 10 lines

Or, if you change the options you used slightly:

alias d="dmesg|grep -iw usb|tail -n 5"

Then you can pass additional -n options:

$ d
# prints 5 lines
$ d -n 10
# prints 10 lines

If multiple -n options are specified for tail, only the last is used.

Solution 2:

You need to have a function for this as described in the SO and here. Try the following:

foo() { /path/to/command "$@" ;}

and call the foo with:

foo arg1 arg2 arg3