Bash 中同名的内部命令和外部命令

昨天有我的在 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/[

相关文章
相关标签/搜索