-1

I once read in a Bash book by O'Reilly the following (my summary):

command and enable

cd () {
    echo "Improved CD !"
    # Improvement one;
    command cd
    # Improvement two;
    # Do cool stuff...
}
cd

The command command is useful when a function containing a builtin is identically named as that builtin - it prevents recursive loop of the builtin in the function;

My question here is why would there be a recursive loop in the first place if we call the function just once?

10

If you try

cd () {
    echo "Improved CD !"
    # Improvement one;
    cd
    # Improvement two;
    # Do cool stuff...
}
cd

without command, cd will call the cd function, which will call the cd function, which will call the cd function, and so on: the cd statement inside the function calls the cd function, not the cd built-in. You’ll see “Improved CD !” repeated ad nauseam in your terminal.

The ultimate result will vary depending on the shell: Zsh will stop (“maximum nested function level reached”), Bash will crash.

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.