【问题标题】:shell - var length with if condition gives errorshell - 带有 if 条件的 var 长度给出错误
【发布时间】:2014-01-17 02:14:42
【问题描述】:

我正在尝试查看是否使用 grep 找到了一些东西

found=`grep -F "something" somefile.txt`

if ((${#found} == 0)); then
   echo "Not Found"
else
   echo "Found"
fi

我成功地使用了上述逻辑,如果 grep 找到了一些东西,它会将输出存储在 found 变量中,但我面临的问题是 if 条件。每当found=0 时,它都会给我一些类似的错误

final.sh: 13: final.sh: 0: 未找到

仅供参考:final.sh 是脚本名称

【问题讨论】:

  • 使用 $?用于检查是否找到

标签: bash shell if-statement grep


【解决方案1】:

问题是您正在编写特定于 bash 的代码,但使用 sh 运行它。在 bash 中,(( .. )) 是一个算术上下文,而在 POSIX sh 中,它只是两个嵌套的子 shell,导致它尝试将数字作为命令执行。

您可以通过在 shebang 中指定 #!/bin/bash 和/或使用 bash yourfile 而不是 sh yourfile 来使用 bash 而不是 sh 来运行它(如果您以这种方式调用它)。

但是,对于您的示例,正​​确的方法是直接使用grep 的退出状态:

if grep -q something somefile
then
  echo "found"
else
  echo "not found"
fi

【讨论】:

    【解决方案2】:

    要检查文件中是否有某个字符串,可以使用 grep 的返回状态

    grep -q something somefile.txt
    if [ $? -eq 0 ]
    then
      echo "found"
    else
      echo "not found"
    fi
    

    更短的形式是

    grep -q something somefile.txt && echo found || echo not found
    

    【讨论】:

      【解决方案3】:
      found=$(grep -F "something" somefile.txt)
      if [ $? = 0 ]; then # $? is the return status of a previous command. Grep will return 0 if it found something, and 1 if nothing was found.
          echo "Something was found. Found=$found"
      else
          echo 'Nothing was found'
      fi
      

      我发现这段代码比其他答案更优雅。
      但无论如何,你为什么要写sh?为什么不使用bash?你确定你需要那种便携性吗? Check out this link 看看你是否真的需要sh

      【讨论】:

        【解决方案4】:

        我是这样做的:

        found=$(grep -F "something" somefile.txt)
        
        if [[ -z $found ]]; then
            echo "Not found"
        else
            echo "Found"
        fi
        

        【讨论】:

        • 感谢 Stabledog,它给出了错误final.sh: 13: final.sh: [[: not found
        • 我猜你正在被 sh 而不是 bash 解析。您可以删除 -z 测试每一侧的一个括号来解决这个问题(sh 没有双括号结构)。或者,您可以将“#!/bin/bash”放在脚本的第一行以调用 bash 而不是 sh。
        • 另外,请注意,我更喜欢 "$( )" 来评估表达式。您还会看到人们使用“` `”(反引号)。反引号的问题在于它们不能嵌套......我也认为它们在混乱的脚本标记中更难被发现。但有些人仍在使用它们。
        猜你喜欢
        • 2017-03-04
        • 2015-08-24
        • 1970-01-01
        • 2012-08-31
        • 1970-01-01
        • 2021-12-12
        • 2022-06-18
        • 2020-01-20
        • 1970-01-01
        相关资源
        最近更新 更多