shell之for、while迴圈

來源:互聯網
上載者:User

標籤:shell

一、for迴圈


[[email protected] shell]# cat for.sh 

#!/bin/bash

for i in `seq 1 10`; do

echo "$i"

 done


通過這個指令碼就可以看到for迴圈的基本結構:

for 變數名 in 迴圈的條件; do     commanddone

[[email protected] shell]# sh for.sh

1

2

3

4

5

6

7

8

9

10


例2:


[[email protected] shell]# cat for2.sh

#!/bin/bash

for a in `ls`; do

echo "$a"

done



[[email protected] shell]# sh for2.sh

case1.sh

case.sh

for2.sh

for3.sh

for.sh

if1.sh

if.sh


例3

[[email protected] shell]# cat for3.sh

#!/bin/bash

for file in `vmstat`; do

echo "$file"

done

for i in `cd /shell && ls`; do 

echo "$i"

done


引用系統命令需要加反引號,其他不用

[[email protected] shell]# for i in 1 4 5 3 a a; do echo "$i"; done

1

4

5

3

a

a




二、while迴圈


[[email protected] shell]# cat while.sh 

#!/bin/bash

a=6

while [ $a -ge 1 ]; do

echo $a

a=$[$a-1]

done


while 迴圈格式也很簡單:

while  條件; do          commanddone

[[email protected] shell]# sh while.sh 

6

5

4

3

2

1



例2

[[email protected] shell]# cat while2.sh 

#!/bin/bash

while :; do

seq 1 3

done


把迴圈條件拿一個冒號替代,這樣可以做到死迴圈

[[email protected] shell]# sh while2.sh 

1

2

3

1

2

3

1

2


本文出自 “不變的時光---胡” 部落格,轉載請與作者聯絡!

shell之for、while迴圈

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.