涉及到比較和判斷的時候,要注意
- 整數比較使用-lt,-gt,ge等比較運算符,詳情參考:整數比較
- 文件測試使用 -d, -f, -x等運算發,詳情參考:文件測試
- 邏輯判斷使用 &&(且)、||(或)、!(取反)
- 字符串比較實用
- 字符串的比較使用以下三個比較運算符:= 或者(==)、!= 、> 、 < 、
- -z表示后面的值是否為空,為空則返回true,否則返回false。
- -n表示判斷后面的值是否為空,不為空則返回true,為空則返回false。
下面的一個例子:
#!/bin/bash #文件名:test.sh read -p 'please input name:' name read -p 'please input password:' pwd if [ -z $name ] || [ -z $pwd ] then echo "hacker" else if [ $name == 'root' ] && [ $pwd == 'admin' ] then echo "welcome" else echo "hacker" fi fi
運行測試:
ubuntu@ubuntu:~$ ./test.sh please input name:root please input password:admin welcome ubuntu@ubuntu:~$ ./test.sh please input name:root please input password: hacker ubuntu@ubuntu:~$ ./test.sh please input name:root please input password:beyond hacker ubuntu@ubuntu:~$
注意:
比較運算符的兩邊都有空格分隔,同時要注意比較運算符兩邊的變量是否可能為空,比如下面這個例子:
#!/bin/bash #文件名:test.sh if [ $1 == 'hello' ];then echo "yes" elif [ $1 == 'no' ];then echo "no" fi
運行:
ubuntu@ubuntu:~$ ./test.sh ./test.sh: line 4: [: ==: unary operator expected ./test.sh: line 7: [: ==: unary operator expected ubuntu@ubuntu:~$ ./test.sh hello yes ubuntu@ubuntu:~$ ./test.sh no no ubuntu@ubuntu:~$ ./test.sh test ubuntu@ubuntu:~$
可以看到,在代碼中想要判斷shell命令的第二個參數是否為hello或者no,但是在測試的時候,如果沒有第二個參數,那么就變成了 if [ == 'hello' ],這個命令肯定是錯誤的了,所以會報錯,比較好的做法是在判斷之前加一個判斷變量是否為空 或者使用雙引號將其括起來,注意,必須使用雙引號,因為變量在雙引號中才會被解析。
#!/bin/bash #文件名:test.sh if [ "$1" == 'yes' ]; then echo "yes" elif [ "$1" == 'no' ]; then echo "no" else echo "nothing" fi
運行:
ubuntu@ubuntu:~$ ./test.sh nothing ubuntu@ubuntu:~$ ./test.sh yes yes ubuntu@ubuntu:~$ ./test.sh no no ubuntu@ubuntu:~$ ./test.sh demo nothing
這樣的話,就不會報錯了。