Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

For bash script, I can use "$@" to access arguments. What's the equivalent when I use an alias?

share|improve this question
add comment

3 Answers 3

up vote 16 down vote accepted

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 "$@"
}
share|improve this answer
1  
opengroup.org/onlinepubs/009695399/utilities/… Functions in sh are defined my_program_wrapper() { ...; }. Bash does handle the keyword function but why not go with what's more portable? –  ephemient Nov 5 '10 at 1:51
1  
@ephemient Very true. I mean besides the fact that everyone uses GNU Bash and not the barebones POSIX shell. –  amphetamachine Nov 5 '10 at 12:53
add comment

You don't have to do anything, actually; aliases do this automatically. For instance:

$ alias less="less -eirqM"
$ less foo.txt

You will see foo.txt's first page, and less will quit at EOF (-e), searches will be case-insensitive (-i), etc.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.