如何專門運行 shell 內建指令

如何專門運行 shell 內建指令

考慮一下我在當前 shell 中執行這些命令或將它們放入其中的情況.bashrc

alias source='echo hi'
alias .='echo hi'
alias unalias='echo hi'

function source(){ echo hi; }等等。

對於二進位命令,我們可以使用絕對路徑,例如:/bin/ls,但是如何在目前 shell 中專門執行這些 shell 內建命令?

答案1

Bash 有這樣的指令builtin

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

Execute SHELL-BUILTIN with arguments ARGs without performing command
lookup.  

例如

$ cat > hello.sh
echo hello
$ source() { echo x ; }
$ source hello.sh
x
$ builtin source hello.sh
hello

builtin但是,沒有什麼可以阻止您重寫。

解決別名(但不是函數)的另一種方法是引用該詞(部分):

$ alias source="echo x"
$ source hello.sh 
x hello.sh
$ \source hello.sh
hello

答案2

始終可以透過引用命令名稱的任何部分來繞過別名,例如\sourceor'source'''sourceor …(除非您也為那些允許的別名定義了別名zsh,但其他 shell 不允許)。

在任何 POSIX shell 中都可以使用command前綴(例如)來繞過函數。command source在 bash 或 zsh 中,您可以使用builtin而不是command強制使用內建函數(如果沒有該名稱的內建函數,則command回退到查找,而在 zsh 中(模擬其他 shell 時除外),完全跳過內建函數)。您可以使用例如取消設定功能。PATHcommandunset -f source

如果您已覆寫或停用所有builtincommandunset,您可能需要放棄將此 shell 執行個體還原為合理狀態的想法。

相關內容