bash – 单行if语句在shell脚本中不起作用

前端之家收集整理的这篇文章主要介绍了bash – 单行if语句在shell脚本中不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的代码
#!/bin/bash
cat input$1 | ./prog$1 > output$1 && if[ "$2" != "" ]; diff output$1 expected$1;

这样会发生:

$./run.sh
./run.sh: line 2: if[ no !=  ]: command not found
$

我以为我可以运行if语句在一行吗?那是什么问题呢?

事实证明,if和[之间需要一个空格.此外,我把当时的关键字和fi.

以下工作.

#!/bin/bash
cat input$1 | ./prog$1 > output$1 && if [ "$2" != "" ]; then diff output$1 expected$1; fi

编辑:

如下所述(和另一个答案),这可以优雅地缩短为:

cat input$1 | ./prog$1 > output$1 && [ "$2" != "" ] && diff output$1 expected$1

在这种情况下,我甚至不必记得有关如何使用if构造的任何规则:)

原文链接:https://www.f2er.com/bash/385149.html

猜你在找的Bash相关文章