shell 迴圈結構

2021-08-25 22:26:01 字數 2789 閱讀 9219

迴圈結構在程式設計中十分常見,也是程式中是較為重要的一部分,在bash中有foruntilwhile這三種語句可以進行重複執行部分程式流程,下面會進一步討論這三個指令的使用以及注意事項

bash中for命令允許使用者建立遍歷乙個系列值的迴圈,在迴圈中,建議執行預先設定好的程式或命令。for的基本格式如下:

for  val in list

do#todo

#commands

done

下面寫幾個簡單的指令碼熟悉一下for的用法。

#!/bin/bash

for i in a b c d e f g

doecho

"i is: $i"

done

i is: a

i is: b

i is: c

i is: d

i is: e

i is: f

i is: g

#!/bin/bash

val=`ls -l /`

for files in

$val

doecho

"output: $files"

done

這裡將根目錄下的檔案列表已**件屬性列印出來,由於預設分隔符號是空格,所以列印的結果如下,由於內容較多,已經省略大部分內容;

output: 總用量

output: 108

output: drwxr-xr-x

output: 2

output: root

output: root

output: 4096

output: 6月

output: 24

output: 20:53

output: bin

output: drwxr-xr-x

output: 4

output: root

output: root

output: 4096

output: 8月

output: 26

output: 06:28

output: boot

output: drwxrwxr-x

使用環境變數ifs可以將分隔符定義為使用者想要使用的分隔符;

#!/bin/bash

val=`ls -l /`

#將分隔符號換成換行符

ifs=$'\n'

for files in

$val

doecho

"output: $files"

done

output: 總用量 108

output: drwxr-xr-x 2 root root 4096 6月 24 20:53 bin

output: drwxr-xr-x 4 root root 4096 8月 26 06:28 boot

output: drwxrwxr-x 2 root root 4096 6月 24 00:07 cdrom

output: drwxr-xr-x 19 root root 4220 8月 25 20:23 dev

bash shell 中可以使用c語言風格的for命令;下例簡單實現了求1+2+3+…+100的和。

#!/bin/bash

sum=0

for (( i=0; i<=100; i++ ))

do sum=$(( $sum + $i ))

done

echo

$sum

bash shell 中的while命令會測試判斷當前的cmd是否返回正確值,當前cmd是否成立,如果成立,則執行迴圈體內的命令,while命令的基本格式如下:

while test cmd

do#todo

#commands

done

通過while簡單實現1至100的求和公式;

#!/bin/bash

i=0sum=0

while [ $i -le 100 ]

do sum=$(($i+$sum))

i=$(( $i+1 ))

done

echo

$sum

until命令與while命令恰恰相反,當cmd命令不成立的時候,則執行迴圈體內部的指令,until命令的基本格式如下:

until test cmd

do#todo

#commands

done

通過until簡單實現1至100的求和公式;

#!/bin/bash

i=0sum=0

until [ $i

-gt100 ]

do sum=$(($i+$sum))

i=$(($i+1))

done

echo

$sum

shell程式設計 迴圈結構

while語句 while語句格式 while 表示式 do command command done while 和 if 的條件表示式完全相同,也是 或commad或test while 表示式 if 表示式 表示式值為0,則迴圈繼續 表示式值為0,then 表示式值為非0,則迴圈停止 表示式值...

shell程式設計 迴圈結構

1 for迴圈語句 for variable in dostatement1 statament2 done 使用省略號的寫法來表示某個範圍 設定步長 for variable in dostatement1 let sum i done 使用字串作為列表元素,可以省略外面的大括號 for i in...

Shell 迴圈結構專題

在shell 101中已經介紹了for迴圈結構,本文做乙個迴圈結構體的總結,補充while,until 兩個迴圈體,以及break,continue關鍵字說明。let s get started.1.for 迴圈 shell 中的for迴圈分為c語言風格的經典for迴圈結構,以及類似python中的...