【问题标题】:How to simplify this bash shell code如何简化这个 bash shell 代码
【发布时间】:2012-03-08 11:52:01
【问题描述】:

这是我的代码

if  grep -q $lines scanHistory;then
    echo -n ''
else
    if grep -q $lines waiting;then
        echo -n ''
    else
        Download $lines
        echo "---$lines was download successfully"
    fi
fi

我的目的是如果在 scanHistory 和 waiting 中都找不到 $line,然后运行 ​​Download。

我试图使这段代码更简单,并将 if 写为

如果 grep -qv $lines scanHistory && grep -qv $lines waiting;那么

....

但是失败了……

【问题讨论】:

  • 失败消息是...?
  • 你可以使用':'而不是使用echo作为无操作,
  • FWIW 你也可以说elif ... fi 而不是else if ... fi; fi,但是William Pursell 有一个更好的答案。

标签: regex bash shell if-statement grep


【解决方案1】:

尝试:

如果 ! grep -q $lines 扫描历史 && ! grep -q $lines 等待;然后 ...

使用 grep -v 的初始尝试失败,因为 如果输入的任何行与模式不匹配,则 grep -v 成功。

【讨论】:

  • 您可以将其压缩为两个文件的单个 grep (if ! grep -q $lines scanHistory waiting; then ...),但在这种情况下,我会说这不太可读,最好让 grep 运行与明确的逻辑分开运行他们。 +1。
【解决方案2】:

也许你想要

  if ! ( grep -q $lines scanHistory || grep -q $lines waiting ) ; then

  ....

问题是 -v 并没有按照你认为的方式工作

当你 grep nonexistant file 时,你得到 1,它没有找到它,但是当你 grep -v nonexistant file 时,返回码是 0,因为 file DID 中的所有其他行都否定匹配'不存在。

我希望这会有所帮助。

【讨论】:

    【解决方案3】:
        grep -q -e "$lines" scanHistory -e "$lines" waiting
        if [ $? -ne 0 ] # Check if the above command is a success or not, if not run downlaod.
        then
            <run_Download>
        fi
    

    【讨论】:

      【解决方案4】:

      使用 bash 短路运算符 &amp;&amp;||

      grep -q $lines scanHistory || 
        grep -q $lines waiting || 
        Download $lines &&
        echo "---$lines was download successfully"
      

      它可以放在一行中,如下所示,但上面的内容更具可读性:

      grep -q $lines scanHistory || grep -q $lines waiting || Download $lines && echo "---$lines was download successfully"
      

      【讨论】:

        猜你喜欢
        • 2011-07-21
        • 1970-01-01
        • 2021-01-09
        • 2011-01-29
        • 1970-01-01
        • 1970-01-01
        • 2011-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多