Shell流程控制語句if

(1).if語句vim

語法格式:bash

if 判斷條件 ; then 
  命令
fi

或
if 判斷條件
then
  命令
fi

if語句流程圖:blog

  實例:判斷命令是否執行成功,成功則輸出語句This is ok.class

[root@youxi1 ~]# vim a.sh
#!/bin/bash
ls /mnt > /dev/null
if [ $? -eq 0 ] ; then
    echo "This is ok."
fi
[root@youxi1 ~]# sh a.sh
This is ok.

(2).雙分支if語句語法

語法格式:im

if 判斷條件 ; then
  命令1
else
  命令2
fi

雙分支if語句流程圖:img

 

 

  實例:判斷命令是否執行成功,成功則輸出This is ok.,不然輸出This is not ok.di

[root@youxi1 ~]# vim a.sh
#!/bin/bash
ls /mnt &> /dev/null
if [ $? -eq 0 ] ; then
    echo "This is ok."
else
    echo "This is not ok."
fi

ls /mnt/a.txt &> /dev/null
if [ $? -eq 0 ] ; then
    echo "This is ok."
else
    echo "This is not ok."
fi
[root@youxi1 ~]# sh a.sh
This is ok.
This is not ok.

(3).多分支if語句鍵盤

語法格式:vi

if 判斷條件1 ; then
  命令1
elif 判斷條件2 ; then
  命令2
elif 判斷條件3 ; then
  命令3
......
else
    命令n
fi

多分支if語句流程圖:

 

  實例:判斷鍵盤輸入的數字,若是等於零則輸出0,若是大於0則輸出「這是一個正數」,若是小於0則輸出「這是一個負數」。

[root@youxi1 ~]# vim a.sh
#!/bin/bash
read -p "請輸入一個數字:" num
if [ $num -eq 0 ] ; then
    echo $num
elif [ $num -gt 0 ] ; then
    echo "這是一個正數"
else
    echo "這是一個負數"
fi
[root@youxi1 ~]# sh a.sh
請輸入一個數字:12
這是一個正數
[root@youxi1 ~]# sh a.sh
請輸入一個數字:0
0
[root@youxi1 ~]# sh a.sh
請輸入一個數字:-12
這是一個負數
相關文章
相關標籤/搜索