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.

How can I write a function in zsh that invokes an existing command with the same name as the function itself? For example, I've tried this to illustrate my question:

function ls 
{
    ls -l $1 $2 $3
}

But I see this when I execute it with ls *:

ls:1: maximum nested function level reached

I assume this is because the function is being called recursively. How I can avoid this?

(this is a crude example, and in this case an alias would do the job, but I have a more complex example where an alias isn't suitable and so I need to write a function).

share|improve this question

2 Answers 2

up vote 11 down vote accepted

What is happening is that you are recursively calling your ls function. In order to use the binary, you can use ZSH's command builtin.

function ls {
    command ls -l "$@"
}
share|improve this answer

Try aliasing (.zshrc): alias l="ls -l $1 $2 $3"

share|improve this answer
    
The parameters $1 $2 $3 are superfluous when defining an alias; just use alias l="ls -l". –  Martin von Wittich Jan 28 at 16:38
    
I was looking for a function-based way of doing this, as I mentioned in the question. –  Andrew Ferrier Jan 28 at 19:14
    
@MartinvonWittich depends on what he is trying to do. (1,2,3 could as well be variables being set in his .zshrc, we do not know.) –  sjas Jan 30 at 22:44
    
@AndrewFerrier indeed. Sometimes what you wish for is not what you need, but maybe you won't know for sure until you are shown something you did not beg for. :) –  sjas Jan 30 at 22:48
    
@sjas Yes, but that's pretty unlikely. While you can directly assign values to positional parameters in zsh (you can't in bash and would have to use set there), to do so would be rather odd. –  Martin von Wittich Jan 30 at 23:38

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.