1.算數判斷
[root@localhost ~]# [ 520 -eq 520 ] 相等
[root@localhost ~]# [ 520 -ne 520 ] 不等於
[root@localhost ~]# [ 520 -gt 1 ] 大於
[root@localhost ~]# [ 520 -ge 520 ] 大於等於
[root@localhost ~]# [ 520 -lt 520 ] 小於
[root@localhost ~]# [ 520 -le 520 ] 小於等於
[root@localhost ~]# echo $?
0
執行完只能看$?的值是否爲0,0爲成功,其他爲失敗
也可直接判斷
((1>=1))
[root@localhost ~]# ((51==51));echo $?
0
2.字符串判斷
[root@localhost ~]# [ "開心" == "開心" ];echo $? 判斷相等
0
[root@localhost ~]# [ "開心" != "開心" ];echo $? 不等
1
[root@localhost ~]# var=123 判斷不爲空
[root@localhost ~]# [ -n "$var" ];echo $?
0
[root@localhost ~]# [ -z "$var" ];echo $? 判斷爲空
1
[root@localhost ~]# [[ "我叫王大力" == *叫* ]];echo $? 判斷包含
0
3.邏輯判斷
[root@localhost ~]# [ 2 -ge 2 -a 3 -ge 3 ];echo $? (這裏-a 代表 and 與)
0
[root@localhost ~]# [ 2 -ge 2 -o 3 -ge 3 ];echo $? (這裏-o 代表 or 或)
0
------------------------------------
其他寫法
[root@localhost ~]# [[ 2 -ge 2 && 3 -ge 3 ]];echo $? (與)
0
[root@localhost ~]# [[ 2 -ge 2 || 3 -ge 3 ]];echo $? (或)
0
非
[root@localhost ~]# [ ! 2 -ge 1 ];echo $? (非)
1
4.內置判斷
tip:結果爲0爲真
判斷當前目錄文件或文件夾存在 -e file
[ -e anaconda-ks.cfg ]
判斷如果文件是一個子目錄 -d file
[ -d anaconda-ks.cfg ];echo $?
判斷文件是否是一個普通文件,不是文件夾 -f file
[ -f anaconda-ks.cfg ]
判斷文件是否可讀 -r file
[ -r anaconda-ks.cfg ];echo $?
判斷文件長度不爲0 -s file
[ -s anaconda-ks.cfg ];echo $?
判斷文件可寫 -w file
[ -x anaconda-ks.cfg ];echo $?
判斷是否是可執行 -x file
[ -x anaconda-ks.cfg ];echo $?
5.邏輯判斷
(1)if語句
語法if:
if [ 邏輯判斷 ];then 執行內容;fi
[root@localhost ~]# if [ 1 -eq 1 ];then echo 我執行了;fi
我執行了
--------------------------------------------------------------
語法if..else:
if [ 邏輯判斷 ];then 執行內容1;else 執行內容2;fi
[root@localhost ~]# if [ 1 -ge 2 ];then echo 執行1;else echo 執行2;fi
執行2
--------------------------------------------------------------
語法if..elseif:
if [ 邏輯判斷 ];then 執行內容1;elif [ 邏輯判斷 ]; 執行內容2;fi
[root@localhost ~]# if [ 1 -eq 2 ]; then echo 執行1 ;elif [ 3 -eq 3 ]; then echo "123";fi
拓展簡寫
1.[ 邏輯判斷 ] && 執行語句 判斷邏輯判斷爲ture,爲true執行後續
[root@localhost ~]# [[ -f anaconda-ks.cfg ]] && echo is file
is file
2.[ 邏輯判斷 ] || 執行語句 判斷邏輯判斷爲false,執行後續
[root@localhost ~]# [[ -d anaconda-ks.cfg ]] || echo is not dir
is not dir
3.[ 邏輯判斷 ] && 執行語句1 || 執行語句2 判斷是否爲ture,爲ture執行第一個,false執行第二個
[root@localhost ~]# [[ -f 123 ]] && echo is not dir || echo is dir
is dir
6.for循環
語句:
for(定義變量;邏輯條件;變量改變);do 執行語句;done
[root@localhost ~]# for((i=0;i<=3;i++));do echo $i;done
0
1
2
3
7.for遍歷循環
語句:
for 變量 in 數組;do 執行語句;done
[root@localhost ~]# for i in ${array[*]};do echo $i ;done
張三
李四
王五
8.while循環
語法:
while [ 邏輯判斷 ];do 執行語句;變量改變;done
[root@localhost ~]# while [ $i -le 3 ];do echo $i;((i=i+1));done
0
1
2
3
tip:按航讀取文件內容
while read line;do echo $line;done < word.txt(文件)
其餘還有退出控制
return 函數返回
exit 腳本退出
break 退出當前循環
continue 跳出當前循環,進入下次循環