1. 程式人生 > >for while until 迴圈使用方法

for while until 迴圈使用方法

for

1.for迴圈

for var(方法) in list
do
commands
done
例:#!/bin/bash
for test in 1 2 3 4 5
do
echo The next number is $test

done
執行結果:
The next number is 1
The next number is 2
The next number is 3
The next number is 4
The next number is 5
每次for命令遍歷值列表,它都會將列表中的下個值賦給$test變數

2.從變數讀取列表

#!/bin/bash
list=“xian beijing shanghai”
list=$list" wuhan"
for city in $list
do
echo “have you ever visited $city?”
done
執行結果:
have you ever visited xian?
have you ever visited beijing?
have you ever visited shanghai?
have you ever visited wuhan?

賦值語句向$list變數包含的已有列表中新增(或者說拼接)了一個值

3.從命令中讀取值

#!/bin/bash
file=“city”
for city in $(cat $file)
do
echo “visit $city”
done
執行結果:
visit shanghai
visit xian
這裡要注意city檔案存在

4.字串處理

#!/bin/bash
for test in “i don’t konw how to use the for command”
do
echo “word:$test”
done
執行結果:
word:i don’t konw how to use the for command
使用雙引號來處理

5.從萬用字元讀取目錄

#!/bin/bash
for file in /*
do
if [ -d “$file” ]
then
echo " $file is a directory"
elif [ -f " $file" ]
then
echo " $file is a file"
fi
done
執行結果:
/app is a directory
/bin is a directory
/boot is a directory
/dev is a directory
/etc is a directory
echo/file1 is a file
/home is a directory
··························

6.C語言風格

#!/bin/bash
for (( i=0; i<10; i++ ))
do
echo “The number is $i”
done
執行結果:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

while

1 #!/bin/bash
var=10
while [ $var -gt 0 ]
do
echo $var
var= $[ $var - 1 ]
done
執行結果:
10
9
8
7
6
5
4
3
2
1
2 #!/bin/bash
n=70
while [ $n -gt 50 ]
do
if [ ((((n%2)) -eq 0 ]
then
echo “偶數:$n”
fi
n= $(( $n-1))
done
執行結果:
偶數:70
偶數:68
偶數:66
偶數:64
偶數:62
偶數:60
偶數:58
偶數:56
偶數:54
偶數:52
只要測試條件成立,while命令就會不停地迴圈執行定義好的命令

until

var=100
until [ $var -eq 0 ]
do
echo $var
var= $[ $var - 25 ]
done
執行結果:
100
75
50
25
until命令和while命令工作的方式完全相反,條件成立時結束。