How to pass parameters to an alias?
Aliases are like commands in that all arguments to them are passed as arguments to the program they alias. For instance, if you were to alias ls
to ls -la
, then typing ls foo bar
would really execute ls -la foo bar
on the command line.
If you want to have actual control over how the arguments are interpreted, then you could write a function like so:
my_program_wrapper() {
local first_arg="$1" \
second_arg="$2"
shift 2 # get rid of the first two arguments
# ...
/path/to/my_program "$@"
}
Alias solution
If you're really against using a function per se, you can use:
$ alias wrap_args='f(){ echo before "$@" after; unset -f f; }; f'
$ wrap_args x y z
before x y z after
You can replace $@
with $1
if you only want the first argument.
Explanation
This creates a temporary function f
, which is passed the arguments.
Alias arguments are only passed at the end. Note that f
is called at the very end of the alias.
The unset -f
removes the function definition as the alias is executed so it doesn't hang around afterwards.
Adding to the present answers, an important thing to realize about how aliases work is that all the parameters you type after an aliased command will be used literally at the end. So there is no way to use alias for two commands (piped or not), out of which the first should interpret the parameters. To make it clear, here's an example of something that would not work as expected:
alias lsswp="ls -l | grep swp"
(an example inspired by this question) this will always use the output of ls -l
performed in the current directory and do a grep on that - so using
lsswp /tmp/
would be equivalent to ls -l | grep swp /tmp/
and not ls -l /tmp/ | grep swp
.
For all purposes where the arguments should be used somewhere in the middle, one needs to use a function
instead of alias
.