【问题标题】:Bash shell `if` command returns something `then` do somethingBash shell `if` 命令返回一些东西 `then` 做某事
【发布时间】:2012-04-29 13:52:52
【问题描述】:

我正在尝试执行 if/then 语句,如果 ls | grep something 命令有非空输出,那么我想执行一些语句。我不知道我应该使用的语法。我已经尝试了几种变体:

if [[ `ls | grep log ` ]]; then echo "there are files of type log";

【问题讨论】:

标签: linux bash if-statement


【解决方案1】:

嗯,差不多了,但是您需要用fi 完成if

另外,if 仅运行命令并在命令成功时执行条件代码(以状态代码 0 退出),grep 仅在找到至少一个匹配项时才会执行此操作。所以你不需要检查输出:

if ls | grep -q log; then echo "there are files of type log"; fi

如果您使用的系统具有不支持 -q(“quiet”)选项的旧版或非 GNU 版本的 grep,您可以通过将其输出重定向到 @ 来获得相同的结果987654328@:

if ls | grep log >/dev/null; then echo "there are files of type log"; fi

但是由于ls 如果找不到指定的文件,它也会返回非零值,所以你可以在没有grep 的情况下做同样的事情,就像在 D.Shawley 的回答中一样:

if ls *log* >&/dev/null; then echo "there are files of type log"; fi

你也可以只使用 shell,甚至不用 ls,虽然它有点冗长:

for f in *log*; do 
  # even if there are no matching files, the body of this loop will run once
  # with $f set to the literal string "*log*", so make sure there's really
  # a file there:
  if [ -e "$f" ]; then 
    echo "there are files of type log"
    break
  fi
done 

只要您专门使用 bash,您就可以设置 nullglob 选项来稍微简化一下:

shopt -s nullglob
for f in *log*; do
  echo "There are files of type log"
  break
done

【讨论】:

    【解决方案2】:

    或者没有if; then; fi:

    ls | grep -q log && echo 'there are files of type log'
    

    甚至:

    ls *log* &>/dev/null && echo 'there are files of type log'
    

    【讨论】:

    • 你的意思是>&,而不是&>
    【解决方案3】:

    if 内置函数执行一个 shell 命令并根据命令的返回值选择块。 ls 如果找不到请求的文件,则返回一个不同的状态代码,因此不需要 grep 部分。 [[ utility 实际上是来自 bash,IIRC 的内置命令,它执行算术运算。我在这方面可能是错的,因为我很少偏离 Bourne shell 语法。

    无论如何,如果你把所有这些放在一起,那么你最终会得到以下命令:

    if ls *log* > /dev/null 2>&1
    then
        echo "there are files of type log"
    fi
    

    【讨论】:

    • 感谢您的解释,但我更愿意使用 grep。我打算过滤几个正则表达式规则,并可能过滤除 ls 之外的其他命令的输出。我以 ls 为例,以便解决我的格式将允许我编写更多类似的命令。干杯,~)
    • @BillyMoon - 您可能需要考虑使用 find 而不是 grepping ls 的输出。如果您确实使用了ls,请使用完整路径,这样您就不会对某人的别名ls 感到惊讶。
    • @D.Shawley 你也可以只使用command ls,它绕过别名和函数,而不依赖于命令的特定路径。
    猜你喜欢
    • 2017-04-16
    • 1970-01-01
    • 2011-12-02
    • 2012-10-15
    • 2012-01-25
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多