公众号旧文
Linux 为什么用 which 而不是 where 来查找可执行文件?
在 Linux 里,我们常用 which 来查找一个命令的路径,比如:
which python
which nginx
胖子我第一次看到时很纳闷:
问东西在哪里,为什么用的是 which,而不是 where?
经过探索,胖子才知道,这背后既有语义差异,也有 Unix 历史原因。
一、英语语义:which 和 where 的区别
在英语里:
- where:问在哪儿
- which:问是多个选项中的哪一个
举个简单例子:
- Where is the restaurant? 餐馆在哪里?
- Which restaurant did you choose? 你选的是哪一家餐馆?
而 Linux 的 which,本质上是在问:
在所有可执行程序里,你调用的是哪一个?
因为在 Linux 系统中,一个命令可能存在 多个版本。
例如:
/usr/bin/python
/usr/local/bin/python
/home/user/bin/python
当你输入:
python
系统会按照 PATH 环境变量顺序去找。
所以 which 的真正含义是:
Which executable will be used?
(系统会用的是哪一个可执行文件?)
因此,用 which 在语义上更准确。
二、Unix 的设计哲学
Linux 继承自 Unix 的传统。
Unix 工具往往遵循一个原则:
命令名尽量短,并且表达功能。
which 的功能很简单:
告诉你 shell 会执行哪个程序。
例如:
which ls
输出:
/usr/bin/ls
意思是:当你输入 ls 时,shell 实际执行的是 /usr/bin/ls 。
三、为什么不用 where?
where 在 Unix 世界里并不常见。
因为在 Unix 体系中,有一个更强大的命令:
type
例如:
type ls
输出可能是:
ls is /usr/bin/ls
或者:
ls is aliased to `ls --color=auto`
甚至:
cd is a shell builtin
这比 which 更准确。
因此很多 Linux 老手更喜欢用:
type
四、有趣的是:Windows 真的用了 where
在 Microsoft Windows 里,微软加入了一个命令:
where
例如:
where python
输出可能是:
C:\Python39\python.exe
C:\Windows\py.exe
Windows 选择 where,是因为它更接近自然语言:
Where is this program located?
而 Unix 选择 which,强调的是:
Which one will be executed?
五、一个很多人不知道的小事实
在很多 Linux 发行版里:
which 其实不是 shell 内建命令。
它只是一个普通程序,例如:
/usr/bin/which
但 type 是 shell 内建命令。
所以在一些极简系统(例如 Alpine Linux)中:
which
可能并不存在。
但 type 一定存在。
六、一句话总结
可以这样理解:
| 命令 | 逻辑 |
|---|---|
| which | 系统会执行哪个程序 |
| where | 程序在哪里 |
Unix 关心的是:
你运行命令时,真正执行的是哪一个文件。
所以最终选择了 which。
扩展阅读: