Ale*_*ird 11 bash scripting if-statement
这是我的代码:
#!/bin/bash
cat input$1 | ./prog$1 > output$1 && if[ "$2" != "" ]; diff output$1 expected$1;
Run Code Online (Sandbox Code Playgroud)
然后发生:
$ ./run.sh
./run.sh: line 2: if[ no != ]: command not found
$
Run Code Online (Sandbox Code Playgroud)
我以为我可以在一行上运行if语句?问题是什么?
Ale*_*ird 18
事实证明,在if和之间需要有一个空间[.另外,我输入then和fi关键字.
以下工作.
#!/bin/bash
cat input$1 | ./prog$1 > output$1 && if [ "$2" != "" ]; then diff output$1 expected$1; fi
Run Code Online (Sandbox Code Playgroud)
编辑:
如下面评论(以及另一个答案),这可以优雅地缩短为:
cat input$1 | ./prog$1 > output$1 && [ "$2" != "" ] && diff output$1 expected$1
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我甚至不必记住有关如何使用if构造的任何规则:)