【问题标题】:find out if a command is included in folders of environment variable PATH查看命令是否包含在环境变量 PATH 的文件夹中
【发布时间】:2015-08-05 07:20:12
【问题描述】:

我不知道如何查看某个命令是否包含在环境变量 PATH 的文件夹中。我尝试了命令:

$type -t $command 

但它不起作用。

谁能帮帮我?

【问题讨论】:

    标签: linux bash shell path environment-variables


    【解决方案1】:

    您的意思是查看您的路径吗?类似于:

    $ 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 指令。 EG if ($command included in PATH) --> 继续编写脚本 else 退出。你明白吗?
    【解决方案2】:

    这应该可行:

    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
    

    commandhelp 是 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本身可能产生的任何输出)。
    • 在 Bash 中,也许还可以查看 hash,如果找不到作为参数提供的命令,它会返回非零值。
    • "type 如果找到任何参数则返回 true,如果没有找到则返回 false。"
    • 你为什么要捕获输出?只需测试其退出状态。
    • 这就是为什么我使用 >& 将标准错误和标准输出都重定向到 /dev/null 的原因。我忽略了任何可见的输出,只查看退出状态。
    猜你喜欢
    • 1970-01-01
    • 2019-05-15
    • 2014-01-20
    • 2019-11-29
    • 2016-10-03
    • 2017-08-30
    • 2019-02-20
    • 1970-01-01
    • 2014-02-15
    相关资源
    最近更新 更多