Bash 在调用shell函数内的内置函数时防止递归

Bash 在调用shell函数内的内置函数时防止递归,bash,shell,cd,Bash,Shell,Cd,我在bashrc中添加了以下函数:- function cd(){ echo "user switching to" $1 cd $1 } 在重新加载.bashrc后,尝试在临时目录(任何目录)中刻录cd时出现以下递归错误:- user switching to temp/ user switching to temp/ user switching to temp/ user switching to temp/ user switching to temp/

我在bashrc中添加了以下函数:-

function cd(){
        echo "user switching to" $1
        cd $1
}
在重新加载.bashrc后,尝试在临时目录(任何目录)中刻录cd时出现以下递归错误:-

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/

我希望方法名为cd,因为每当用户使用cd命令时,我希望执行一些逻辑。

您可以在bash中使用
内置的
命令:

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

cd
的选项也有限
$1
不一定是新工作目录的名称。
内置cd“$@”
会更健壮。仅供参考,
函数
关键字是非标准的,并且限制了代码的可移植性。要使用所有POSIX shell,请将其删除,然后从
cd(){
开始定义函数。