標籤: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迴圈