標籤:
for迴圈的文法:
1. for 變數 in 值1 值2 值3....
do
程式
done
例如:下列指令碼會分別列印4次 分別是morning noon afternoon evening的值
1 #!/bin/bash2 #列印時間3 #Author Mrfeng4 5 for time in morning noon afternoon evening6 do7 echo $time8 done
例如批量解壓縮:
1 #!/bin/bash 2 #批量解壓縮指令碼 3 #Author: Mrf 4 5 path=/opt/lamp 6 7 cd $path 8 9 ls *.tar.gz > ls.log10 ls *.tgz >> ls.log11 for i in $(cat ls.log)12 do13 tar zxvf $i &>>cc.log14 done15 rm -rf ls.log
2.for 文法二
格式:
1 for ((初始值;迴圈控制條件;變數變化))2 do3 程式4 done
例如:
1 #!/bin/bash2 #從1加到1003 4 s=05 for(( i=1;i<=100;i=i+1 ))6 do7 s=$(($s+$i))8 done9 echo "the sum of 1+2+...+100is: $s"
例如:大量新增使用者
1 #!/bin/bash 2 # 大量新增使用者數量的使用者 3 # Author:Mr f (E-mail:22222222) 4 5 read -p "Please input user name:" -t 30 name 6 read -p "Please input the number of users:" -t 30 num 7 read -p "Please input the password of users:" -t 30 pass 8 if [ ! -z "$name" -a ! -z "$num" -a ! -z "$pass" ] 9 then10 y=$(echo $num | sed ‘s/[0-9]//g‘)11 if [ -z "$y" ] ; then12 for ((i=1;i<=$num;i=i+1))13 do14 /usr/sbin/useradd $name$i &>/dev/null15 echo $pass | /usr/bin/passwd --stdin $n16 ame$i &>/dev/null17 done18 fi19 fi20 cat /etc/passwd | grep user[1-$num] | cut -d ":" -f 1 >>userlist.log
當然我也寫了一個利用 userlist.log進行大量刪除的指令碼方便大家做完實驗後清理
1 #!/bin/bash2 for i in $(cat ./userlist.log)3 do4 /usr/sbin/userdel -r $i &>>del.log5 done6 #cat del.log7 rm -rf del.log
shell學習之路:流程式控制制(for)