在linux下使用的非常常见的几个搜索相关的命令,这里总结一些其使用的场景以及局限性和优点。

which命令

使用说明:
which命令之所以被列为搜索命令,那是因为它的使用频度。which用来列出通过参数传递过来的可执行文件名的包含路径的文件名全称。

它的左右只有两个条件同时满足时才能起效。

  • 条件1: 可执行文件或者系统内置命令
  • 条件2: 文件所在的目录在PATH的搜索目录列表中

使用示例如下所示:

[root@host121 ~]# which pwd
/bin/pwd
[root@host121 ~]# which hostname
/bin/hostname
[root@host121 ~]# which cd
/bin/cd
[root@host121 ~]# which ls
alias ls='ls --color=auto'
	/bin/ls
[root@host121 ~]#

type命令

使用说明:
基本跟which大体类似的功能,主要用于确认命令是否是shell内置的功能还是独立的功能,其余几乎类似,只是输出结果显示方式略有不同而已

使用示例如下所示:

[root@host121 ~]# type pwd
pwd is a shell builtin
[root@host121 ~]# type hostname
hostname is /bin/hostname
[root@host121 ~]# type cd
cd is a shell builtin
[root@host121 ~]# type ls
ls is aliased to `ls --color=auto'
[root@host121 ~]#

而file命令才是用来确认一个可执行文件是二进制,还是脚本方式的文本。使用示例如下所示:

[root@host121 ~]# file /bin/ls
/bin/ls: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=ceaf496f3aec08afced234f4f36330d3d13a657b, stripped
[root@host121 ~]#

whereis 命令

使用说明:
基本跟which大体类似的功能。但是将搜索范围扩展到二进制文件、man说明文件、参数文件以及源码文件等。

使用具体示例如下所示:

[root@host121 ~]# whereis pwd
pwd: /usr/bin/pwd /usr/share/man/man1/pwd.1.gz
[root@host121 ~]# whereis hostname
hostname: /usr/bin/hostname /etc/hostname /usr/share/man/man1/hostname.1.gz /usr/share/man/man5/hostname.5.gz
[root@host121 ~]# whereis cd
cd: /usr/bin/cd /usr/share/man/man1/cd.1.gz
[root@host121 ~]# whereis ls
ls: /usr/bin/ls /usr/share/man/man1/ls.1.gz
[root@host121 ~]#

locate

使用说明:
从保存的文件信息数据库中根据关键字或者表达式进行内容搜索,详细使用方法可参看:

  • 使用限制
    需要自行安装此命令,无法实时确认文件信息,比如新删除和新创建的文件,如果没有执行updatedb命令更新locate检索的文件信息数据库,则无法争取返回结果,所有可能会有一定的缓冲区是无法正确搜索出来的。
  • 优点与缺点
    速度快,使用方法简单。不受权限的影响,普通用户也能确认所有信息,因为就是到文件数据库中就查询一下而已,不过这也是一个问题,权限的控制,那些信息能查出来那些不让查出来,控制的不是很好。

find

使用说明:
几乎可以完成所有的搜索功能,还可以跟xargs与管道符结合起来完成更强大的功能。但是使用起来选项复杂,另外不同操作系统的实现方式在细节选项上多有不同。

使用示例如下:

[root@host121 ~]# find . -type f |grep nexus |grep 3.19.1
./easypack/containers/standard/nexus/Dockerfile.3.19.1
[root@host121 ~]# 
[root@host121 ~]# find . -name '*ockerfile*' |xargs grep centos7.7.1908
./easypack/containers/alpine/jenkins/Dockerfile.centos7.7.openjdk1.8.jenkins2.164.3:FROM centos:centos7.7.1908
[root@host121 ~]#

当然使用方法非常之多,这里只是随手举出2个常用的使用方法而已,find的功能非常强大,使用也非常之多,前面一些命令搜索不出来或者不正确的时候,则可以考虑使用find来完成,但是前提是用户有相应查询的权限。