Linux學習總結(五十九)shell腳本2-邏輯判斷if

1 三種基本if語句

格式1:if 條件 ; then 語句; fishell

#!/bin/bash
a=5
if [ $a -gt 2 ];
then echo $a
fi

執行結果爲 5
格式2:if 條件; then 語句; else 語句; fibash

#!/bin/bash
a=5
if [ $a -gt 10 ];then 
echo $a
else 
echo 0
fi

執行結果爲 0
格式3:if …; then … ;elif …; then …; else …; fiide

#!/bin/bash
a=8
if [ $a -lt 2 ];then
    echo $a
elif [ $a -gt 10 ];then
    echo 10
else
    echo 0
fi

執行結果爲0
備註:if邏輯判斷,自上而下知足條件執行相應操做後馬上結束。不知足則繼續往下判斷,直到知足條件爲止。
邏輯判斷表達式:if [ $a -gt $b ]; if [ $a -lt 5 ]; if [ $b -eq 10 ]等 -gt (>); -lt(<); -ge(>=); -le(<=);-eq(==); -ne(!=) 注意處處都是空格
能夠使用 && || 結合多個條件
if [ $a -gt 5 ] && [ $a -lt 10 ]; then
if [ $b -gt 5 ] || [ $b -lt 3 ]; thencode

二 if 判斷文件、目錄屬性

[ -f file ]判斷是不是普通文件,且存在
[ -d file ] 判斷是不是目錄,且存在
[ -e file ] 判斷文件或目錄是否存在
[ -r file ] 判斷文件是否可讀
[ -w file ] 判斷文件是否可寫
[ -x file ] 判斷文件是否可執行
幾種特殊的判斷
if [ -z "$a" ] 這個表示當變量a的值爲空時會怎麼樣
if [ -n "$a" ] 表示當變量a的值不爲空
if grep -q '123' 1.txt; then 表示若是1.txt中含有'123'的行時會怎麼樣
if [ ! -e file ]; then 表示文件不存在時會怎麼樣
if (($a<1)); then …等同於 if [ $a -lt 1 ]; then…
[ ] 中不能使用<,>,==,!=,>=,<=這樣的符號input

三 shell 中的case 判斷

格式 case 變量名 in
value1)
command
;;
value2)
command
;;
*)
commond
;;
esac
在case程序中,能夠在條件中使用|,表示或的意思, 好比 2|3) command ;;
舉例it

#!/bin/bash
read -p "Please input a number: " n
case $n in
1)
    ls /root/
;;
2)
    fdisk -l
;;
3)
   ifconfig
;;
esac

以上腳本運行後就能夠輸入1或2或3執行相應的命令。class

相關文章
相關標籤/搜索