bash:为什么source命令实际上运行该功能?以及如何避免呢?

我在.bashrc文件中定义了一个函数

function test(){
  echo "test function is run"
}

每当我尝试获取.bashrc文件的源文件以获取最近进行的一些更新时,我都注意到该功能实际上已经运行了两次。

[myusername@myserver:~]$ source ~/.bashrc
test function is run
test function is run

真烦人 我以为source命令只能加载功能。 为什么要运行它? 以及如何避免呢? 谢谢。

评论
  • oqui
    oqui 回复

    This is happening because you have existing code in your .bashrc (or invoked from your .bashrc) that calls test. That might sound strange — why is it already calling a function you've just created? — but it's because test is also the name of a command that's built into Bash [link], and the existing code is trying to use that command. By overriding test with your function, you're tricking that later code into calling your function instead of the built-in command.

    To fix this, rename your function to something other than test, so as not to interfere with that later code.