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.

I was wanting to maybe alias a command such that the command ran as per usual but also did something else on the argument/s before it was executed. An example might be:

alias ls="echo displaying contents of $@; ls $@"

Just a hypothetical, but essentially I was wanting to run a command (ls in this case) and have a static command set to run on it before the standard ls happens.

A function like:

function ls() {
echo "printing $1"
ls $1
}

didn't seem to be appropriate since I would have to handle switches/options being used on the command in question, i.e., recreating the whole command.

PS. I want to use the original command how it is normally used just add functionality to it in the way described above using something like alias or rc (ie something that I can attach permanently)

share|improve this question
3  
This question sounds like it could be a case of the XY problem. It may be better to ask a question about what you actually want to achieve with the mechanism you're seeking. –  Thomas Nyman Sep 12 '13 at 10:09
add comment

3 Answers 3

up vote 4 down vote accepted

You can use "$@" to pass all function arguments as they are to the actual command:

$ verbose_ls() { echo "running ls with args '$@'"; \ls "$@"; }
$ alias ls=verbose_ls
$ ls -l -a /
running ls with args '-l -a /'
...

Note the backslash \ before the ls in the function. This will keep bash from expanding the ls alias, since you want to invoke the /bin/ls, not the alias you defined recursively.

If you actually want to access a particular argument in the function while still retaining the ability pass arbitrary option switches to the actual command, you probably can't avoid implementing some kind of argument parsing logic into the function itself.

share|improve this answer
add comment

It cannot be done with an alias: http://mywiki.wooledge.org/BashFAQ/080

share|improve this answer
add comment

You can use :

ls() {
     echo "printing ${1}"
     command ls "${1}"
}
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.