【发布时间】:2015-08-05 07:20:12
【问题描述】:
我不知道如何查看某个命令是否包含在环境变量 PATH 的文件夹中。我尝试了命令:
$type -t $command
但它不起作用。
谁能帮帮我?
【问题讨论】:
标签: linux bash shell path environment-variables
我不知道如何查看某个命令是否包含在环境变量 PATH 的文件夹中。我尝试了命令:
$type -t $command
但它不起作用。
谁能帮帮我?
【问题讨论】:
标签: linux bash shell path environment-variables
您的意思是查看您的路径吗?类似于:
$ set | grep PATH
哦,现在我明白了。检查路径中的可执行文件相当容易。我通常使用如下内容:
## test for exe in PATH or exit
exevar="$(which exe 2>/dev/null)"
[ x = x$exevar ] && { echo "'exe' not in path"; exit 1; }
## exe in path, continue
echo "exevar = $exevar"
或使用type -p 消除对which 的调用
## test for exe in PATH or exit
exevar="$(type -p exe 2>/dev/null)"
[ x = x$exevar ] && { echo "'exe' not in path"; exit 1; }
## exe in path, continue
echo "exevar = $exevar"
【讨论】:
这应该可行:
if [[ $(type -p command) ]]; then
echo "Found"
else
echo "Not Found"
fi
您也可以使用-t(请参阅底部的例外情况。
或者(只用type测试退出状态):
if type command >& /dev/null; then
echo "Found"
else
echo "Not Found"
fi
注意:见底部的例外情况。
另一种解决方案(使用hash):
if [[ ! $(hash command 2>&1) ]]; then
echo "Found"
else
echo "Not Found"
fi
注意:见底部的例外情况。
例外情况:
type command
type help
hash command
hash help
type -t command
type -t help
command 和 help 是 bash 内置的,它们不在 PATH 环境变量的任何路径中。因此,除了第一个方法(带有-p 选项)之外的其他方法将打印出 Found 用于不在环境 PATH 变量中的任何路径中的 bash 内置命令。
如果您只想检查它是否位于 PATH 环境变量中的路径中,最好使用第一种方法(带有-p 选项)。
或者如果你想使用type -t,那么改变 if 语句如下:
if [[ $(type -t command) == file ]]; then
【讨论】:
type的输出,只测试退出状态:if ! type command >& /dev/null; then(输出重定向会抑制type本身可能产生的任何输出)。
hash,如果找不到作为参数提供的命令,它会返回非零值。