Linux或Unix中`Which command` 命令介绍及实例

174 阅读2分钟

Which command 是一个经常使用的命令,用于查找linux/unix中可执行文件的位置。

在应用程序开发过程中,我可以使用这个命令来定位tomcat的位置,以便查找日志。

在本教程中,我们将学习该命令的语法和使用实例。

语法

which options [string array]

该命令接受:

  • 选项
  • -a 显示给定输入字符串的所有路径名
  • 字符串是一个输入文件名,与PATH文件夹路径进行比较和检查。

返回文件名的路径列表

在返回这个命令之前,它返回以下退出代码 0 - 给定的文件名与可执行路径相匹配 1 - 文件名没有被发现可执行 2 - 如果一个选项是无效的参数,它将返回。

打印每个参数的所有匹配路径名,该命令搜索配置在环境变量PATH中的可执行文件。

PATH是一个环境变量,它包含所有指向可执行文件的目录。

首先使用echo命令打印PATH的环境值

$:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

例如,要检查git命令在linux机器上的安装位置

$:~$ which git
/usr/bin/git

在/usr/bin文件夹中找到git命令的可执行文件

哪些命令选项

请看下面有选项和无选项的例子

-a 选项打印所有与给定输入字符串匹配的路径名

$:~$ which git
/usr/bin/git

$:~$ which -a git
/usr/bin/git
/bin/git

$:~$ 

打印哪条命令的文档info which command

WHICH(1)                                        General Commands Manual                                       WHICH(1)
NAME
       which - locate a command
SYNOPSIS
       which [-a] filename ...
DESCRIPTION
       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 canonicalize path names.
OPTIONS
       -a     print all matching pathnames of each argument
EXIT STATUS
       0      if all specified commands are found and executable
       1      if one or more specified commands is nonexistent or not executable
       2      if an invalid option is specified
       

有时which命令不起作用,或者没有在控制台返回任何信息

那么你可以使用whereis命令,与which语法相同。

总结

这篇文章展示了如何清除不同操作系统的终端命令。