linux中对文件进行查找主要使用的就是标题中的四个命令,为什么会提供四个命令,当然是因为他们彼此功能上存在差异,下面就简单介绍一下这四个命令的特点.
which
which returns the pathnames of the files (or links) which would be executed in the current environment, had its arguments been given as commands in a strictly POSIX-conformant shell. It does this by searching
the PATH for executable files matching the names of the arguments. It does not follow symbolic links.
从上面的说明我们可以知道,which只查找当前用户PATH环境变量(可以通过echo $PATH查看)下的可执行文件,这样的话范围就比较窄,当然速度也是飞起.
whereis
whereis locates the binary, source and manual files for the specified command names. The supplied names are first stripped of leading pathname components and any (single) trailing extension of the form .ext(for example: .c) Prefixes of s. resulting from use of source code control are also dealt with. whereis then attempts to locate the desired program in the standard Linux places, and in the places specified by $PATH and $MANPATH.
whereis命令只能用于程序名的搜索,而且只搜索二进制文件(参数-b)、man说明文件(参数-m)和源代码文件(参数-s)。如果省略参数,则返回所有信息。
和find相比,whereis查找的速度非常快,这是因为linux系统会将 系统内的所有文件都记录在一个数据库文件中,当使用whereis和下面即将介绍的locate时,会从数据库中查找数据,而不是像find命令那样,通 过遍历硬盘来查找,效率自然会很高。
但是该数据库文件并不是实时更新,默认情况下时一星期更新一次,因此,我们在用whereis和locate 查找文件时,有时会找到已经被删除的数据,或者刚刚建立文件,却无法查找到,原因就是因为数据库文件没有被更新。
locate
locate文件用于查找文件(包括普通文件),他与全盘搜索的find命令的区别是locate依赖于一个已经建好的并且每天进行更新的数据库.这样的话也会存在whereis存在的问题,就是数据库可能不是最新的,会缺少文件或者存在已经被删除的文件.但是它带来的确实速度上的大幅度提升,大家自己去感受一下就知道了.locate支持正则表达式匹配
当然我们也可以手动去更新这个数据库,只要在任意目录下运作sudo updatedb命令即可.
find
这个命令就像我们在windows下面的搜索了,进行的是在指定目录下的扫描,速度会稍微慢一点.
find可用的参数非常多,支持正则表达式匹配.
如果我们不知道要找的文件在那个目录下,那就用根目录/去找吧,如:
find / -name filename -print
上面的命令意思是在全局中查找名字为filename的文件或者文件名,找到之后print出来