Bash 中同名的内部命令和外部命令
昨天有个人在 bug-bash 上问:为什么 [ --help 没有输出帮助信息。有人回答他了,原因是 coreutils 提供的 [ 命令才接受 --help 选项,Bash 自己的 [ 命令不接受任何选项。当你在 Bash 里执行 [ --help 时,当然优先执行的是内部命令 [,而不是外部命令 [,执行 /usr/bin/[ --help(在我的 Mac 上是在 /bin/[)才能获得他想要的帮助信息。
其实除了 [,还有一些其它外部命令也会和 Bash 提供的内部命令同名,下面列举一下在我电脑上找到的这样的命令的名字:
[
alias
bg
cd
command
echo
false
fc
fg
getopts
hash
jobs
kill
printf
pwd
read
test
time
true
type
ulimit
umask
unalias
wait
另外,从 Bash 4.4 开始,大部分的内部命令都开始接受 --help 选项,举两个例子,比如以前的 eval 和 source 是这样的:
eval --help bash: eval: --: invalid option eval: usage: eval [arg ...] source --help bash: source: --: invalid option source: usage: source filename [arguments] |
而在 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 命令:
span style="line-height: 1.5">$ 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/[ |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2012-09-23 [译]JavaScript:void运算符