1. 程式人生 > >[Bash]syntax error near unexpected token 'then'

[Bash]syntax error near unexpected token 'then'

#!/bin/bash
clear
function test
{
   if[$1 -eq "root"]&&[$2 -eq "123456"]
      then
          echo "Right"
      else
          echo "Wrong"
   fi
}
test root 123456

上面這個程式我執行時,報這個錯誤,剛接觸shell,沒想到它的語法這麼……不說了,在網上找個原因,貼出正確的格式,並總結要注意的幾點

#!/bin/bash
clear
function test
{
   if [[ "$1"-eq"root"&&"$2"-eq"123456" ]]
      then
          echo "Right"
      else
          echo "Wrong"
   fi
}
test root 123456

總結:

1.if後要有空格

2.[] 中括號的開頭和結尾要有空格!

3. [ $1-eq"root" ]中括號中的$1和-eq和"root"之間沒有空格!

如果採用雙中括號,又是另外一種規則:

1.if後要有空格

2.[[]] 中括號的開頭和結尾要有空格!

3. [ $1-eq"root" ]中括號中的$1和-eq和"root"之間可以有或沒有空格!