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)

  • 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

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.


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


You can use :

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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