1、條件判斷if語句
1)、 單分支
if 判斷條件;then
條件為真的分支代碼
fi
2)、雙分支
if 判斷條件; then
條件為真的分支代碼
else
條件為假的分支代碼
fi
逐條件進行判斷,第一次遇為“真”條件時,執行其分支,而后結束整個if語句
例如:if ping -c1 -W2 station1 &> /dev/null; then
echo 'Station1 is UP'
elif grep "station1" ~/maintenance.txt &> /dev/null;then
echo 'Station1 is undergoing maintenance’
else
echo 'Station1 is unexpectedly DOWN!'
exit 1
fi
2、條件判斷case語句
case 變量引用 in
PAT1)
分支1
;;
PAT2)
分支2
;;
…
*)
默認分支
;;
Esac
case 支持glob風格的通配符(正則表達式):
*: 任意長度任意字符
?: 任意單個字符
[]:指定范圍內的任意單個字符
a|b: a或b
3、練習題示例
1)、寫一個腳本/root/bin/createuser.sh ,實現如下功能:使用一個用戶名做為參數,如果指定參數的用戶存在,就顯示其存在,否則添加之;顯示添加的用戶的id 號等信息
#!/bin/bash
if grep “^$1\>” /etc/passwd >> /dev/dull;then
echo “the username exists”
exit
else
useradd $1
getent passwd $1
fi
2)、寫個腳本/root/bin/yesorno.sh ,提示用戶輸入yes或no, 并判斷用戶輸入的是yes還是no, 或是其它信息
第一種方法:
#!/bin/passwd
read -p "please input the yes or no:" a
if [ $a == yes ];then
echo "yes"
elif [ $a == y ];then
echo "yes"
elif [ $a == Y ];then
echo "yes"
elif [ $a == YES ];then
echo "yes"
elif [ $a == no ];then
echo "no"
elif [ $a == n ];then
echo "no"
elif [ $a == N ];then
echo "no"
elif [ $a == NO ];then
echo "no"
else
echo "other"
fi
第二種方法:
#!/bin/bash
read –p “please inout yes or no:” a
case $a in
[yY]|[yY][Ee][sS])
echo “yes”
;;
[Nn]|[Nn][Oo])
echo “no”
;;
*)
echo “other”
;;
esac
注意case語句:
case支持glob風格的通配符(正則表達式):
*: 任意長度任意字符
?: 任意單個字符
[]:指定范圍內的任意單個字符
a|b: a或b
第三種方法:
#!/bin/bash
read -p "please inout yes or no:" a
ans=`echo $a|tr 'A-Z' 'a-z'`
if [ $ans == yes -o $ans == y ]
then
echo "yes"
elif [ $ans == no -o $ans == n ]
then
echo "no"
else
echo "other"
fi
3)、寫腳本/root/bin/filetype.sh, 判斷用戶輸入文件路徑,顯示其文件類型(普通,目錄,鏈接,其它類型)
第一種方法:
#!/bin/bash
read -p "please input the file path:" a
[ ! -e $a ] && echo "the file not exist" && exit
if [ -f $a ];then
echo "this file is common"
elif [ -d $a ];then
echo "this file is directory"
elif [ -h $a ];then
echo "this file is link"
else
echo "this file is other"
fi
4)、寫一個腳本/root/bin/checkint.sh, 判斷用戶輸入的參數是否為正整數
首先如何用已有知識表示正整數,注意01也是正整數,可以用正則表達式0*[1-9][0-9]*
#!/bin/bash
read -p "please input the argument:" a
if [[ $a =~ ^0*[1-9][0-9]*$ ]];then
echo "this arg is zzshu"
else
echo "this arg isn't zzshu"
fi
原創文章,作者:18612763863,如若轉載,請注明出處:http://www.www58058.com/35572