這是我的代碼:單行如果在一個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
$
我以爲我可以運行,如果在一行語句?這是什麼問題?
這是我的代碼:單行如果在一個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
和[
之間需要有一個空格。另外,我在then
和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
構造的規則:)
刪除if。 []會產生一個新的「命令」,你可以運行差異或任何後,如果它退出0使用& &(如果先前退出運行下一個好運行)。在這裏:
echo lol && [ $((10-1)) -eq 9 ] && echo math\!
和你的一行:
#!/bin/bash
cat input$1 | ./prog$1 > output$1 && [ "$2" != "" ] && diff output$1 expected$1
... as thr4wn已評論 – 2012-02-27 00:00:40
您可以縮短這一點:'./prog$1 < input$1 >輸出$ 1 && [ 「$ 2」= 「」!] && diff的輸出$ 1預計$ 1' – 2012-02-24 20:37:10