【问题标题】:single-line if statement in a shell script not workingshell脚本中的单行if语句不起作用
【发布时间】:2012-03-15 07:03:40
【问题描述】:

这是我的代码:

#!/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 语句?这就是问题所在吗?

【问题讨论】:

    标签: bash scripting if-statement


    【解决方案1】:

    原来if[ 之间需要有一个空格。另外,我输入了thenfi 关键字。

    以下工作。

    #!/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 构造的规则:)

    【讨论】:

    • 你可以缩短一点:./prog$1 < input$1 > output$1 && [ "$2" != "" ] && diff output$1 expected$1
    【解决方案2】:

    放弃如果。 [] 将产生一个新的“命令”,如果使用 && 以 0 退出,您可以运行 diff 或其他任何内容(如果先前退出正常,则运行下一个)。这里:

    echo lol &&  [ $((10-1)) -eq 9 ] && echo math\!
    

    和你的单线:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多