if的[]和[[]]

[]是bash裏test的同義詞,比如[ -d filename ]和test -d filename的結果是一樣的,邏輯測試使用-a、-o
[[]]比[]通用,邏輯測試使用&&、||

#!/bin/bash
x=$1
if [ -d $x ];then
        echo ok
else
        echo "not equel"
fi
----------------------------
[root@localhost shelltest]# test -d /root && echo ll
ll

在[]裏面,使用-eq的時候,需要用整數來做參數,如果是非整數就會提示報錯,而[[]]則直接把非整數的字符串轉成了0(),而不會去檢查並顯示報錯內容。

if [ $x -eq $y ]時
[root@localhost shelltest]# ./teststring.sh 1 ad
./teststring.sh: line 4: [: ad: integer expression expected
當if [[ $x -eq $y ]]時
[root@localhost shelltest]# ./teststring.sh ad ad
ok
[root@localhost shelltest]# ./teststring.sh 1 a
not equel
[root@localhost shelltest]# ./teststring.sh aa 0
ok
[root@localhost shelltest]# ./teststring.sh 0 aa
ok

[]和[[]]都不支持+-*/數學運算符

整數的比較
注意前面都是有個符號-

eq等於
ne不等於
gt大於
ge大於等於
lt小於
le小於等於
例
if [ $x -eq $y ]
if [[ $x -gt $y ]]
if [ "$x" -eq "$y" ]
if [[ "$x" -eq "$y" ]]
>大於
>=大於等於
<小於
<=小於等於
例
if [[ $x > $y ]]
if (( $x > $y ))
注:if [ $x > $y ]會一直爲true,可以改成if [ $x \> $y ],也就是把符號>轉義(包括字符串(**ASCII中對應的順序大小**)和整數)。(if [ "$x" \> "$y" ])

字符串的比較
=等於,效果和==是一樣的

if [ $x = $y ]
if [[ $x = $y ]]
if [ $x == $y ]
if [[ $x == $y ]]
if [[ $x = "abc" ]]

-z測試是否爲空,爲空則爲true

if [ -z "$x" ]
if [ -z $x ]

-n測試是否不爲空,不爲空則爲true

if [ -n "$x" ]

注:需要有雙引號,負責一直爲true

發佈了44 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章