shell腳本之七:if結構條件句知識與實踐

7、if結構條件句知識與實踐

(一)if條件句單雙分支語法

一、單分支
if 條件
   then
   指令
fi
二、雙分支
if 條件
   then
   指令
else
   指令集2
fi

(二)if條件句多分支語句

一、語句的結構

if 條件1
   then
   指令1
elif 條件2
   then
   指令2
elif 條件3
   then
   指令3
else
   指令4   
fi

二、實例:判斷目錄是否存在

若是不存在目錄/backup,則建立。
[root@centos6-kvm3 scripts]# cat 07-01.sh
#!/bin/bash
path="/backup"
[ -d $path ] || mkdir $path -p
if [ -d $path ]
then
   :(冒號表示什麼都不作)
else
  mkdir $path -p
fi

if [ !-d $path]
then
  mkdir $path -p
fi
[root@centos6-kvm3 scripts]#

三、實例:判斷服務器內存大小

開發shell腳本判斷內存是否充足,若是小於100,提示不足,若是大於100提示充足。
[root@centos6-kvm3 scripts]# cat 07-02.sh 
#!/bin/bash
mem=`free -m | awk 'NR==3{print $NF}'`
if [ $mem -lt 100 ]
then
   echo "內存不充足!"
else
   echo "內存充足!"
fi
[root@centos6-kvm3 scripts]#

四、實例:判斷兩個整數大小

[root@centos6-kvm3 scripts]# cat 07-03.sh
#!/bin/bash
read -p "請輸入兩個整數:" a b
expr $a + $b + 1 &>/dev/null
if [ $? -ne 0 ]
then
   echo "請輸入兩個整數。"
   exit 0
fi
if [ -z "$b" ]
then
  echo "請輸入兩個整數。"
  exit 1
fi

if [ $a -lt $b ]
then
   echo "$a小於$b"
elif [ $a -gt $b ]
then
   echo "$a大於$b"
else
   echo "$a等於$b"
fi
若是使用傳參方式:
[$# -ne 2 ]判斷參數是否爲兩個。

五、實例:打印一個安裝菜單

[root@centos6-kvm3 scripts]# cat 07-04.sh
#!/bin/bash
cat <<EOF
1.install lamp
2.install lnmp
3.exit
EOF
read -p "請輸入一個數字{1|2|3}:" n
expr $n + 2 &>/dev/null
if [ $? -ne 0 ]
then
   echo "usage:$0{1|2|3}"
   exit 0
fi

if [ $n -eq 1 ]
then
   echo "install lamp"
elif [ $n -eq 2 ]
then
   echo "install lnmp"
elif [ $n -eq 3 ]
then
   echo "exit"
else
   echo "usage:$0{1|2|3}"
fi
[root@centos6-kvm3 scripts]#
相關文章
相關標籤/搜索