Linux shell之三種For 循環結構
1. 列表for 循環
for variable in {list}
do
command
command
done
cat for_exam1.sh
#!/bin/bash
for varible1 in 1 2 3 4 5
do
echo "hello ,welcome $varible1 times"
done
執行:./for_exam1.sh
hello ,welcome 1 times
hello ,welcome 2 times
hello ,welcome 3 times
hello ,welcome 4 times
hello ,welcome 5 times
注:for 循環支持縮略計數
for varible1 in {1..5} #只能用兩個點做為省略號
do
echo "hello ,welcome $varible1 times"
done
#for循環支持按規定的步數跳躍
cat for_exam3.sh
#!/bin/bash
#對sum賦初值
sum=0
#使用列表for循環計算1~100內所有的奇數之和,並將值保存在sum中
for i in {1..100..2}
do
let "sum+=i"
done
#輸出sum值
echo "sum=$sum"
#for循環用seq命令支持按步數遞增
#!/bin/bash
#對sum賦初值
sum=0
#使用列表for循環計算1~100內所有的奇數之和,並將值保存在sum中
for i in $(seq 1 2 100)
do
let "sum+=i"
done
#輸出sum值
echo "sum=$sum"
#當前目錄下所有文件的顯示
#!/bin/bash
#ls顯示當前目錄下所有文件的顯示
for file in $( ls )
do
echo "file:$file"
done