2011-02-02 62 views
4
#! /bin/bash 

count=1 
step=(a b) 

for x in 0 1 
do 
    if [[ $count != '0' ]]; then 
     if [[ ${step[x]} = "a"]]; then 
      echo "Python test ($count)" 
     else 
      echo "stress test" 
     fi 
    fi 
done 

我收到以下錯誤bash腳本:怎樣才能使用嵌套如果在一個for循環

syntax error in conditional expression: unexpected token `;' 
line 20: syntax error near `; 
line 20: `  if [[ ${step[x]} = "a"]]; then' 

爲什麼?

+1

第9行如何成爲第20行? – ocodo 2011-02-02 22:15:57

回答

5

您需要在第二個if"a"]]之間的空格。

從技術上講,[[]]必須是單獨的標記,並且bash的解析器不會在引號或大多標點符號上分隔標記。

我相信你的原始代碼的行相當於if [[ ${step[x]} = "a]]"; then如果這使問題更加明顯。

1

變化

if [[ ${step[x]} = "a"]]; then 

if [[ ${step[$x]} = "a" ]]; then 

代替 x使用$x的最後一個參數後面添加一些空間。

更新:您不需要在數組下標(也在雙括號(())let關鍵字之後)中輸入$登錄的變量前面。

+1

它適用於我在有和沒有$前面的x。 – GreenMatt 2011-02-02 22:14:00