腳本中的if條件判斷和循環
在linux下,寫腳本是我們必不可少的。在寫腳本的過程中,if判斷和各種的循環是我們常用的。這里,詳細的說一下條件判斷以及循環的使用。
條件判斷:if 和 else
1.if
shell程序中的條件分支是通過if條件語句來實現的,其格式一般為if -then -fi ,這樣的是單分支語句,還有的一種就是if-then-else-fi兩種。
(1)if-then語法格式: #由于粘貼圖片易亂格式,為方便觀看,我直接附上正解源碼,帶結果
if 命令行
then
命令行
fi
(2)if-then-else-fi語法格式
if CONDITION1; then
if-true
elif CONDITION2; then
if-ture
elif CONDITION3; then
if-ture
…
else
all-false
fi
這個主要還是通過案例,多練習才能熟練的使用。下面我會做一些案例供參考。
2.case
if條件語句用于在兩個選項中選定一項,而case條件選擇為用戶提供了根據字符串或變量的值從多個選項中選擇一項的方法,其格式為:
case string in
pat1)
command1
;;
pat2)
command2
;;
……
*)
other command
esac
其中case支持使用shell的通配符("*","?","[]"),通常用*作為case命令的最后運算式以便在前面找不到相應的匹配項時執行“其他命令行”的命令。
1、寫一個腳本/root/bin/createuser.sh,實現如下功能:
使用一個用戶名做為參數,如果指定參數的用戶存在,就顯
示其存在,否則添加之;顯示添加的用戶的id號等信息
[root@localhost 0812]# ls /home
alice bash basher gentoo gentoo1 kk nologin test1 testbash tom
[root@localhost 0812]# bash iftest1.sh
Please input one username:kk
The user is exist
uid=1000(kk) gid=1000(kk) groups=1000(kk),10(wheel)
[root@localhost 0812]# bash iftest1.sh
Please input one username:zz
Add zz finished
uid=2018(zz) gid=2018(zz) groups=2018(zz)
[root@localhost 0812]# ls /home
alice bash basher gentoo gentoo1 kk nologin test1 testbash tom zz
[root@localhost 0812]# cat iftest1.sh
#!/bin/bash
#
read -p "Please input one username:" username
if grep ^$username.* /etc/passwd &> /dev/null ;then
echo "The user is exist"
echo "`id $username`"
else
useradd $username
echo "Add $username finished"
echo "`id $username`"
fi
[root@localhost 0812]#
2、寫一個腳本/root/bin/yesorno.sh,提示用戶輸入yes或
no,并判斷用戶輸入的是yes還是no,或是其它信息
read -p "please enter [yes] or [no]:" so
case $so in
[Yy]|[Yy][Ee][Ss])
echo your choice is yes! ;;
[Nn]|[Nn][Oo])
echo your choice is no! ;;
*)
echo unknown ;;
esac
3、寫一個腳本/root/bin/filetype.sh,判斷用戶輸入文件路
徑,顯示其文件類型(普通,目錄,鏈接,其它文件類型)
#參考下面的/var/下文件的判斷
4、寫一個腳本/root/bin/checkint.sh,判斷用戶輸入的參數
是否為正整
[root@localhost 0812]# vi 判斷參數.sh
[root@localhost 0812]# bash 判斷參數.sh
Please input one number:
At least input one number
[root@localhost 0812]# bash 判斷參數.sh
Please input one number:ee
“error”
[root@localhost 0812]# bash 判斷參數.sh
Please input one number:55
The num type is int
[root@localhost 0812]# cat 判斷參數.sh
#!/bin/bash
#
read -p 'Please input one number:' num
if [ -z $num ];then
echo "At least input one number "
exit 1
fi
if [[ $num =~ ^[1-9]{1,} ]];then
echo "The num type is int"
else
echo “error”
fi
[root@localhost 0812]#
3.for
for 變量名 in 列表;do
循環體
done
?
依次將列表中的元素賦值給“變量名”; 每次賦值后即執行一次循環體; 直到列表中的元素耗盡,循環結束
列表生成方式:
(1) 直接給出列表
(2) 整數列表:
(a) {start..end}
(b) $(seq [start [step]] end)
(3) 返回列表的命令
$(COMMAND)
(4) 使用glob,如:*.sh
(5) 變量引用;$@, $*
1、判斷/var/目錄下所有文件的類型
[root@localhost d0816]# vi 查看文件類型2.sh
[root@localhost d0816]# bash 查看文件類型2.sh
The account type is :d
The adm type is :d
The cache type is :d
The crash type is :d
The db type is :d
The empty type is :d
The games type is :d
The gopher type is :d
The kerberos type is :d
The l2a type is :f
The lib type is :d
The local type is :d
The lock type is :d
The log type is :d
The mail type is :d
The nis type is :d
The opt type is :d
The preserve type is :d
The run type is :d
The spool type is :d
The tmp type is :d
The yp type is :d
[root@localhost d0816]# ls /var
account cache db games kerberos lib lock mail opt run tmp
adm crash empty gopher l2a local log nis preserve spool yp
[root@localhost d0816]# cat 查看文件類型2.sh
#!/bin/bash
#
for name in `ls /var/.`
do
if [ -f /var/$name ];then
echo "The $name type is :f"
elif [ -d /var/$name ];then
echo "The $name type is :d"
elif [ -h /var/$name ];then
echo "The $name type is :link"
else
echo "The $name type is :other"
fi
done
2、添加10個用戶user1-user10,密碼同用戶名
[root@localhost bin]# cat adduser.sh
#!/bin/bash
#
for num in `seq 1 10`;do
if id user$num&>/dev/null;then
echo "user$num exist!";continue
else
useradd user$num&&echo "user$num"|passwd –stdin user$num
fi
done
? 3、/etc/rc.d/rc3.d目錄下分別有多個以K開頭和以S開頭的
文件;分別讀取每個文件,以K開頭的文件輸出為文件加stop
,以S開頭的文件輸出為文件名加start;
“K34filename stop”
“S66filename start”
[root@localhost d0816]# vi KS.sh
[root@localhost d0816]# bash KS.sh
K50netconsole stop
S10network start
[root@localhost d0816]# cat KS.sh
#!/bin/bash
#
for name in `ls /etc/rc.d/rc3.d`
do
if [[ $name =~ ^K.* ]];then
echo "$name stop"
fi
if [[ $name =~ ^S.* ]];then
echo "$name start"
fi
done
? 4、寫一個腳本,提示輸入正整數n的值,計算1+2+3+…n的
總和
[root@localhost d0816]# bash 1-n和.sh
Please input int number:5
The 1-5的和為:15
[root@localhost d0816]# bash 1-n和.sh
Please input int number:3
The 1-3的和為:6
[root@localhost d0816]# cat ./1
100sum.sh 1-n和.sh
[root@localhost d0816]# cat ./1-n和.sh
#!/bin/bash
#
read -p 'Please input int number:' num
if [ $num -lt 1 ];then
echo "Aleast input one number"
exit 1
fi
sum=0
for n in $(seq 1 $num)
do
let sum=$sum+$n
done
echo "The 1-$n的和為:$sum"
? 5、寫一個腳本,提示請輸入網絡地址,如192.168.0.0,判
斷輸入的網段中主機在線狀態
[root@localhost bin]# cat updown.sh
#!/bin/bash
#
read -p "please enter a ip address:" ipaddr
ip=`echo "$ipaddr"|egrep -o "^[[:digit:]]{1,3}\.[[:digit:]]{1,3}."`
#echo "$ip"
echo
nu=0
nd=0
#for i in `seq 0 254`;do
for j in `seq 1 255`;do
if ping -W1 -c1 ${ip}252.${j} &>/dev/null ;then
let nu++
echo -e "\n\t\t${ip}252.${j} is up $nu"
else
let nd++
echo -e "\b\r$nd down"
fi
done
#done
4.while
while CONDITION; do
循環體
done
? CONDITION:循環控制條件;進入循環之前,先做一次判斷;每一次循環之后會再次做判斷;條件為“true”,則執行
一次循環;直到條件測試狀態為“false”終止循環.
5.until
? until CONDITION; do
循環體
? done
? 進入條件: CONDITION 為false
? 退出條件: CONDITION 為true
1、求100以內所有正整數之和
[root@localhost bin]# cat sum100.sh
#!/bin/bash
#
i=1
while [ $i -le 100 ];do
let s=s+i
let i++
done
echo "$s"
2、通過ping命令探測172.16.250.1-254范圍內的所有主機
的在線狀態,統計在線主機和離線主機各多少。
[root@localhost until]# cat ping10.sh
#!/bin/bash
#
i=1
NumUp=0
NumDown=0
echo
until [ $i -gt 254 ];do
if ping -W1 -c1 10.1.252.$i &>/dev/null ;then
let NumUp++
echo -e "\n\t\t 10.1.252.$i is up $NumUp"
else
let NumDown++
echo -e "\b\r$NumDown down"
fi
let i++
done
? 3、打印九九乘法表
#!/bin/bash
#
i=1
j=1
while [ $i -le 9 ]
do
for j in `seq 1 $i`
do
echo -ne "$j*$i=$[i*j]\t"
done
let i++
echo
done
4、利用變量RANDOM生成10個隨機數字,輸出這個10數字
,并顯示其中的最大者和最小者
[root@localhost bin]# vi random.sh
[root@localhost bin]# bash random.sh
19182
The max number is 29660,The min number is 1200
[root@localhost bin]# cat random.sh
#!/bin/bash
#
i=1
random=$RANDOM
max=$random
min=$random
echo "$random"
while [ $i -le 10 ]
do
random=$RANDOM
if [[ $random -ge $max ]];then
max=$random
fi
if [[ $random -le $min ]];then
min=$random
fi
let i++
done
echo "The max number is $max,The min number is $min"
? 5、打印國際象棋棋盤
root@localhost bin]# cat chess.sh
#!/bin/bash
#
line=1
i=8
while [ $line -le 8 ] ;do
j=$line
while [ $j -le $i ] ;do
co=$[$j%2]
if [ $co -eq 1 ];then
echo -ne "\033[47m \033[0m"
else
echo -ne "\033[40m \033[0m"
fi
let j++
done
echo
let line++
let i++
done
原創文章,作者:zhong,如若轉載,請注明出處:http://www.www58058.com/37090