目录

1. which

2. whereis 

3. command -v 

4. type

5. hash

判断


1. which

which filename

按文件名查找。which会在用户设置的PATH目录中查询,所以也可以查询系统命令。
有结果返回0,没有结果返回1。

Shell查看命令状态及位置_查找命令

2. whereis 

whereis filename

根据文件名查找,会列出所有位置。

Shell查看命令状态及位置_hash表_02

3. command -v 

command -v <the_command>

POSIX兼容。根据命令名搜索。
有结果返回0,没有结果返回1,可用来做判断。

Shell查看命令状态及位置_hash表_03

4. type

 type <the_command>
 type -p                 只显示路径

shell内建。根据命令名搜索。
有结果返回0,没有结果返回1,可用来做判断。

Shell查看命令状态及位置_搜索_04

5. hash

hash <the_command>        将查询结果加入hash表
hash -t <the_command>     打印命令路径
hash -l                   显示hash表
hash -r                   清空

会先将搜索结果存到hash表,可以查看或打印hash表。
有结果返回0,没有结果返回1,可用来做判断。

Shell查看命令状态及位置_搜索_05

判断

gnudate() {
    if hash gdate 2>/dev/null; then
        gdate "$@"
    else
        date "$@"
    fi
}
$ command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }
$ type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }
$ hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed.  Aborting."; exit 1; }
command -v gpg &>/dev/null && 
    echo "gpg found at  $(command -v gpg)" || 
    echo "Cound not find gpg. Aborting."
gpg=$(command -v gpg 2>/dev/null) && 
    echo "gpg found at $gpg." ||
    echo "Cound not find gpg. Aborting."