shell學習之路:流程式控制制(for)

來源:互聯網
上載者:User

標籤:

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)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.