天天看點

shell 關于==,[[ 錯誤

代碼如下:

#!/bin/sh
a=10
b=20
echo "a=$a,b=$b"
if [ $a == $b ] 
then
  echo "a == b"
else
  echo "a != b"
fi
if [[ $a -eq 10 && $b -eq 20 ]] 
then
  echo "a==10 && b==20"
else
  echo "a!=10 || b!=20"
fi
      

結果運作如下:

linux@ubuntu:~/test_shell$ ./hello.sh 
a=10,b=20
./hello.sh: 6: [: 10: unexpected operator
a != b
./hello.sh: 12: ./hello.sh: [[: not found
a!=10 || b!=20
      

注意:

1,條件表達式要放在方括号之間,并且要有空格,例如: 

[$a==$b]

 是錯誤的,必須寫成 

[ $a == $b ]

2,邏輯運算符 && 與 ||  要用 [[ ]]

查詢其版本如下,也不低:

linux@ubuntu:~/test_shell$ bash --version
GNU bash, version 4.2.24(1)-release (i686-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
      

後來發現:

#!/bin/sh      

改成下面的就可以了:

#!/bin/bash      

備注:

Shell 程式設計跟java、php程式設計一樣,隻要有一個能編寫代碼的文本編輯器和一個能解釋執行的腳本解釋器就可以了。

Linux的Shell種類衆多,常見的有:

  • Bourne Shell(/usr/bin/sh或/bin/sh)
  • Bourne Again Shell(/bin/bash)
  • C Shell(/usr/bin/csh)
  • K Shell(/usr/bin/ksh)
  • Shell for Root(/sbin/sh)
  • ……

一般使用的是 Bash,也就是 Bourne Again Shell,由于易用和免費,Bash在日常工作中被廣泛使用。同時,Bash也是大多數Linux系統預設的Shell。

#!/bin/sh,它同樣也可以改為#!/bin/bash。

但在ubuntu裡最好用#!/bin/bash

#!告訴系統其後路徑所指定的程式即是解釋此腳本檔案的Shell程式。

繼續閱讀