如何专门运行 shell 内置命令

Rav*_*ina 2 bash alias shell-builtin

考虑一种情况,我在当前的 shell 中运行这些命令,或者将它们放在里面.bashrc

alias source='echo hi'
alias .='echo hi'
alias unalias='echo hi'
Run Code Online (Sandbox Code Playgroud)

或者function source(){ echo hi; },等等。

在二进制命令的情况下,我们可以使用绝对路径,例如:/bin/ls,但是我如何在当前 shell 中专门运行这些 shell 内置命令中的任何一个?

ilk*_*chu 7

Bash 有这样的命令builtin

builtin: builtin [shell-builtin [arg ...]]
Execute shell builtins.

Execute SHELL-BUILTIN with arguments ARGs without performing command
lookup.  
Run Code Online (Sandbox Code Playgroud)

例如

$ cat > hello.sh
echo hello
$ source() { echo x ; }
$ source hello.sh
x
$ builtin source hello.sh
hello
Run Code Online (Sandbox Code Playgroud)

但是,没有什么可以阻止您覆盖builtin

另一种解决别名(但不是函数)的方法是引用(部分)这个词:

$ alias source="echo x"
$ source hello.sh 
x hello.sh
$ \source hello.sh
hello
Run Code Online (Sandbox Code Playgroud)


Gil*_*il' 5

总是可以通过引用命令名称的任何部分来绕过别名,例如\sourceor'source'''sourceor ……(除非您已经为那些定义了别名zsh,但其他 shell 不允许)。

在任何 POSIX shell 中都可以使用command前缀(例如command source)绕过函数。在 bash 或 zsh 中,您可以使用builtin而不是command强制使用内置函数(如果没有该名称的内置函数,则command回退到PATH查找,而在 zsh 中(模拟其他 shell 时除外),command完全跳过内置函数)。您可以使用例如取消设置功能unset -f source

如果您已经覆盖或禁用了所有builtin,commandunset,您可能需要放弃将此 shell 实例恢复到合理状态的想法。