Search code examples
bashshellcd

Preventing recursion when calling a builtin inside a shell function


I added below function in bashrc :-

function cd(){
        echo "user switching to" $1
        cd $1
}

after reloading .bashrc, attempt to cd in temp directory (any directory) gives below recursive error :-

user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/
bash: echo: write error: Bad address
user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/
user switching to temp/

I want the method name to be cd, as i want to execute some logic, whenever user uses cd command.


Solution

  • You can use the builtin command in bash :

    function cd(){
            echo "user switching to $1"
            builtin cd "$@"
    }