昨天有我的在 bug-bash 上問:爲何 [ --help 沒有輸出幫助信息。有人回答他了,緣由是 coreutils 提供的 [ 命令才接受 --help 選項,Bash 本身的 [ 命令不接受任何選項。當你在 Bash 裏執行 [ --help 時,固然優先執行的是內部命令 [,而不是外部命令 [,執行 /usr/bin/[ --help(在個人 Mac 上是在 /bin/[)才能得到他想要的幫助信息。html
其實除了 [,還有一些其它外部命令也會和 Bash 提供的內部命令同名,下面列舉一下在我電腦上找到的這樣的命令的名字:shell
[
alias
bg
cd
command
echo
false
fc
fg
getopts
hash
jobs
kill
printf
pwd
read
test
time
true
type
ulimit
umask
unalias
waitbash
另外,從 Bash 4.4 開始,大部分的內部命令都開始接受 --help 選項,舉兩個例子,好比之前的 eval 和 source 是這樣的:ui
$ eval --helpspa bash: eval: --: invalid option htm eval: usage: eval [arg ...]get $ source --helpinput bash: source: --: invalid optionstring source: usage: source filename [arguments]hash |
而在 Bash 4.4 裏是這樣的:
$ eval --help eval: eval [arg ...] Execute arguments as a shell command. Combine ARGs into a single string, use the result as input to the shell, and execute the resulting commands. Exit Status: Returns exit status of command or success if command is null. $ source --help source: source filename [arguments] Execute commands from a file in the current shell. Read and execute commands from FILENAME in the current shell. The entries in $PATH are used to find the directory containing FILENAME. If any ARGUMENTS are supplied, they become the positional parameters when FILENAME is executed. Exit Status: Returns the status of the last command executed in FILENAME; fails if FILENAME cannot be read. |
我在 Bash 4.4 alpha 裏試了一下,仍有少部分命令不接受 --help 選項,下面是我猜的緣由:先說 echo,echo --help 只能輸出 --help,輸出別的就有兼容性問題了。還有一些命令好比 true false :,多是由於自古以來這些命令就不接受任何選項吧,還有 test 和 [,我就不知道爲何了。
另外說個知識點,就是上面提問題的那我的還回貼說:我是經過 which [ 確認了在 Bash 裏執行的 [ 是個外部命令的。隨即有人糾正他,不能用 which 來判斷一個命令是內部命令仍是外部命令,由於 which 自己就是個外部命令,它的工做原理就是在 PATH 裏查找外部命令,它不可能知道 [ 在 Bash 裏是個內部命令,應該用 type 命令:
$ which [ /bin/[ $ type [ [ is a shell builtin |
並且 type 命令還能夠把內部命令和外部命令按照 Bash 的查找順序同時列出來:
$ type -a [ [ is a shell builtin [ is /bin/[ |
最後再說一句,在 zsh 裏 which 是個內部命令,並且它的功能和 type 很相似:
$ zsh $ which -a [ [: shell built-in command /bin/[ |