目录
1. which
which filename
按文件名查找。which会在用户设置的PATH目录中查询,所以也可以查询系统命令。
有结果返回0,没有结果返回1。
2. whereis
whereis filename
根据文件名查找,会列出所有位置。
3. command -v
command -v <the_command>
POSIX兼容。根据命令名搜索。
有结果返回0,没有结果返回1,可用来做判断。
4. type
type <the_command>
type -p 只显示路径
shell内建。根据命令名搜索。
有结果返回0,没有结果返回1,可用来做判断。
5. hash
hash <the_command> 将查询结果加入hash表
hash -t <the_command> 打印命令路径
hash -l 显示hash表
hash -r 清空
会先将搜索结果存到hash表,可以查看或打印hash表。
有结果返回0,没有结果返回1,可用来做判断。
判断
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."