1. 條件選擇 if 語句
選擇執行:
? 單分支
if 判斷條件: then
條件為真的分支代碼
fi
? 雙分支
if 判斷條件; then
條件為真的分支代碼
else
條件為假的分支代碼
fi
? 多分支
if CONDITION1; then
if-true
elif CONDITION2; then
if-ture
elif CONDITION3; then
if-ture
…
else
all-false
fi
? 逐條件進行判斷,第一次遇為“真”條件時,執行其分支,而后結束整個if語句
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
2.條件判斷: case 語句
case 變量引用 in
PAT1)
分支1
;;
PAT2)
分支2
;;
…
*)
默認分支
;;
esac
3.練習:
1、寫一個腳本/root/bin/createuser.sh,實現如下功能:
使用一個用戶名做為參數,如果指定參數的用戶存在,就顯
示其存在,否則添加之;顯示添加的用戶的id號等信息
read "input your username :" input_user
id $input_user
if [ $? -eq 0 ] ;then
echo" user exist"
else
useradd $input_user
chk_id=`getent passwd $input_user | cut -d: -f 3 `
echo $chk_id
fi
? 2、寫一個腳本/root/bin/yesorno.sh,提示用戶輸入yes或
no,并判斷用戶輸入的是yes還是no,或是其它信息
#!/bin/bash
#
read -p "please input yes or no:" input_info
[ -z "$input_info" ] && (echo "error";exit) || uperr_input_info=`echo "$input_info" | tr [a-z] [A-Z]`
case $uperr_input_info in
Y|YES|NO|N)
echo "right"
;;
*)
echo "other info "
;;
esac
3、寫一個腳本/root/bin/filetype.sh,判斷用戶輸入文件路
徑,顯示其文件類型(普通,目錄,鏈接,其它文件類型)
#!/bin/bash
#
read -p "please input the path :" path_file
if [ -z "$path_file" ];then
echo "you need to input info";exit
else
type_file=`ls -ld $path_file | cut -c1`
echo "the type of the file is : $type_file"
fi
4、寫一個腳本/root/bin/checkint.sh,判斷用戶輸入的參數
是否為正整數
#!/bin/bash
#
read "please input int:" int_put
if [[ "$int_put" =~ '^[1-9]+$' ]] ;then
echo "it is a int"
elif [ "$int_put" -le 0 ] ;then
ehco "it is fu int or zero"
elif [ "$int_put" -eq 0 ];then
echo "it is zero"
else
echo "it is not a int"
fi
#也可以使用 expr a + 0 ,即可判斷a的類型
原創文章,作者:ldt195175108,如若轉載,請注明出處:http://www.www58058.com/36346