【问题标题】:Shell script works in bash but not in kshShell 脚本在 bash 中有效,但在 ksh 中无效
【发布时间】:2011-10-07 12:31:06
【问题描述】:

我需要编写一个脚本来测试 blablabla 命令是否存在于类路径中。于是我写了如下代码:

if ! hash blablabla >/dev/null 2>&1; then
   echo not found
fi

当脚本在 bash 中执行时,这可以正常工作。但是如果我在 KSH 中尝试,那就不行了:

#! /usr/bin/ksh

if ! hash blablabla >/dev/null 2>&1; then
   echo not found
fi

我希望echo not found 被执行,但我什么也没得到。有什么问题?

【问题讨论】:

    标签: bash shell ksh


    【解决方案1】:

    我相信 command 是可移植的(如果重要的话):

    command -v -- some_command >/dev/null 2>&1 ||
      printf '%s\n' "not found"  
    

    【讨论】:

    • @glenn jackman,是的,感谢您指出。一些 shell 将其实现为 wherece 别名,但它是标准的。
    【解决方案2】:

    在 bash 中 hash 是一个内置命令。在 ksh 中,它是一个别名;别名在 shell 脚本中不活跃。

    alias hash='alias -t --'
    

    试试which 命令,它是一个外部命令,因此与shell 无关:

    if ! which -s blablabla; then
        echo not found >&2
    fi
    

    【讨论】:

    • 关于 hash 是 KSH 的别名是对的。谢谢(你的)信息!但不幸的是 which 命令在我正在使用的服务器中没有 -s。
    【解决方案3】:

    hash 命令是bash 中的shell 内置命令,但ksh 中没有。您可能想改用whence。

    if ! whence blah; then print urgh; fi  
    

    【讨论】:

    • 只对 ksh 可用的来源。我也需要它来处理 bash。
    • @Rodrigo:为什么?你在写剧本吗?在这种情况下,只需在顶部用一个 hash-bang (#!) 指定要在哪个 shell 中运行脚本,例如,#!/bin/ksh 以使用 Korn shell。我将不同的 shell 视为不同的编程语言。这样我就不会尝试制作polyglot 程序。这往往会使脚本更简洁。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多