which命令依赖$PATH查找可执行文件,用于确定当前执行的命令路径;whereis则在固定系统目录中查找命令的二进制文件、源码和手册页,不依赖$PATH,适合了解命令的完整安装信息。两者互补,which适用于确认运行路径,whereis适用于全面了解命令分布。

在Linux系统里,要找到一个命令的实际位置,我们通常会用到
which
whereis
which
$PATH
whereis
在Linux中定位命令,理解其背后的机制是关键。我们日常操作中,当在终端输入一个命令并回车时,shell会按照特定的规则去寻找并执行它。这其中,
which
whereis
which
$PATH
举个例子:
$ which python3 /usr/bin/python3
这表明当我输入
python3
/usr/bin/python3
而
whereis
$PATH
/bin
/usr/bin
/sbin
/usr/sbin
man
src
whereis
例如:
$ whereis ls ls: /usr/bin/ls /usr/share/man/man1/ls.1.gz /usr/share/man/man1p/ls.1p.gz
这里不仅找到了
ls
理解这两者的工作机制,就能在不同的场景下选择最合适的工具。如果你只是想知道当前环境下哪个命令会被执行,
which
whereis
which
which
$PATH
git
git
$PATH
$PATH
git
which
那么,为什么
which
一个很普遍的情况是,你尝试查找的命令它压根儿就不是一个独立的可执行文件,而是一个shell内置命令(比如
cd
echo
alias
.bashrc
.zshrc
which
type
比如:
$ which cd # 什么都不输出,或者提示 cd not found $ type cd cd is a shell builtin
另一个原因就是,那个命令的可执行文件确实存在,但它所在的目录不在你当前的 $PATH
/opt/mytool/bin
$PATH
/opt/mytool/bin
which mytool
$PATH
还有一种情况是,你查找的是一个别名(alias)。别名是为了方便用户自定义命令的缩写或带参数的命令组合。例如,你可能设置了
alias ll='ls -alF'
which ll
type
$ alias ll='ls -alF' $ which ll # 什么都不输出 $ type ll ll is aliased to `ls -alF'
最后,当然就是最直接的原因:这个命令根本就不存在,或者你拼写错了。在这种情况下,
which
which
whereis
which
whereis
whereis
which
which
$PATH
whereis
$PATH
这个区别导致了它们在应用场景上的差异:
搜索范围和目的不同:
which
$PATH
whereis
对环境变量的依赖:
which
$PATH
whereis
$PATH
输出内容不同:
which
whereis
那么,何时应优先使用
whereis
当你需要查找一个命令的man手册页时:这是
whereis
grep
man grep
$ whereis grep grep: /usr/bin/grep /usr/share/man/man1/grep.1.gz
这清晰地告诉你
grep
当你怀疑一个命令可能安装了,但不在你的 $PATH
$PATH
which
whereis
当你需要查找一个命令的源代码时:虽然不常见,但某些开源工具在安装时会保留源代码。如果你想研究某个命令的实现细节,
whereis
当你需要确认一个系统级命令的“官方”位置时:对于
/bin
/usr/bin
whereis
$PATH
总而言之,
which
whereis
which
whereis
除了
which
whereis
一个非常强大的工具是
type
which
$ type ls
ls is aliased to `ls --color=auto'
$ type cd
cd is a shell builtin
$ type my_custom_func
my_custom_func is a function
my_custom_func ()
{
echo "This is my custom function."
}
$ type python3
python3 is /usr/bin/python3type
另一个与
which
command -v
which
$PATH
command -v
command -v
which
$ command -v ls ls $ command -v python3 /usr/bin/python3 $ command -v ll alias ll='ls -alF'
注意
command -v ls
ls
command -v
/usr/bin/ls
which
command -v -- /bin/ls
当你的目标不再仅仅是“命令”,而是任何类型的文件,并且你知道文件名(或部分文件名),但不知道它在哪个目录下时,
find
find
$PATH
find
例如,在根目录下查找所有名为
nginx
$ find / -name nginx -type f 2>/dev/null
这里
2>/dev/null
最后,如果你系统安装了
mlocate
locate
/var/lib/mlocate/mlocate.db
updatedb
locate
$ locate python3 | grep bin /usr/bin/python3 /usr/bin/python3.10 /usr/bin/python3.8 ...
这些工具各有千秋,理解它们的特点和适用场景,能让你在Linux的世界里游刃有余,快速定位所需信息。
以上就是如何在Linux中查找命令 Linux which与whereis区别的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号