过程式编程
选择执行
顺序执行: if, case
循环执行: for, while, until
for循环列表
1
2
3
4
5
6
7
8
|
for i in LIST; do
循环体
done for i in LIST
do 循环体
done |
while循环
1
2
3
4
5
6
7
8
9
10
11
12
|
while CONDITION; do
循环体
done while CONDITION
do 循环体
done CONDITION 循环控制条件,每执行一次循环体,需要再次进行判断 true 时,执行一次循环
false 时,退出循环
|
练习:100以内所有正整数之和
练习: 100以内所有偶数和
练习:添加10个用户
练习:通过ping命令探测172.16.250.1-254范围内的所有主机的在线状态.用while循环
练习:打印9x9乘法表
练习:利用RANDOM生成10个随机数,输出这10个数字,并显示其中最大者和最小者
练习:100以内所有正整数之和
1
2
3
4
5
6
7
8
|
#!/bin/bash # declare -i sum =0
for i in {1..100}; do
let sum =$ sum +1
done echo $i
echo "summary: $sum"
|
1
2
3
4
5
6
7
8
9
10
11
|
#!/bin/bash # declare -i sum= 0
declare -i i= 1
while [ $i -le 100 ]; do
sum=$[$sum+$i]
let i++
done echo $i echo "summary: $sum"
|
练习: 100以内所有偶数和
1
2
3
4
5
6
7
8
9
10
11
|
#!/bin/bash # declare -i sum= 0
declare -i i= 2
while [ $i -le 100 ]; do
sum=$[$sum+$i]
let i+= 2
done echo $i echo "summary: $sum" |
练习:添加10个用户user1-user10
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/bin/bash # declare -i i=1
declare -i users =0
while [ $i - le 10 ]; do
id user$i &> /dev/null
retval=$?
[ $retval - ne 0 ] && useradd user$i &> /dev/null
[ $? - eq 0 ] && echo "Add user user$i finished" && let users =$ users +1
done echo "Add $users users"
|
练习:通过ping命令探测172.16.250.1-254范围内的所有主机的在线状态.用while循环
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#!/bin/bash # declare -i IP= '172.16.250.'
declare -i i= 1
declare -i uphosts= 0
declare -i downhosts= 0
while [ $i -le 254 ]; do
if ping -c 1 -w 1 $IP$i &> /dev/ null ; then
echo "$IP$i is up"
let uphosts++
else
echo "$IP$i is down"
let downhosts++
fi
done echo "uphosts: $uphosts"
echo "downhosts: $downhosts"
|
练习:打印9x9乘法表
1
2
3
4
5
6
7
8
9
|
#!/bin/bash # for i in { 1 .. 9 }; do
for j in $(seq 1 1 $i); do
echo -ne "${j}X${i}=$[$i*$j]\t"
j=$(($j+ 1 ))
done
echo
done |
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/bin/bash # declare -i i= 1
while [ $i -le 9 ]; do
declare -i j= 1
while [ $j -le $i ]; do
echo -ne "${j}X${i}=$[$i*$j]\t"
j=$(($j+ 1 ))
done
echo
i=$(expr $i + 1 )
done |
练习:利用RANDOM生成10个随机数,输出这10个数字,并显示其中最大者和最小者
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
#!/bin/bash # declare -i max= declare -i min= declare -i i= 1
declare -i random while [ $i -le 10 ]; do
random=$RANDOM
echo $random
if [ $i -eq 1 ]; then
max=$random
min=$max
fi
if [ $i -gt 1 ]; then
if [ $random -gt $max ]; then
max=$random
fi
if [ $random -lt $min ]; then
min=$random
fi
fi
let i++
done echo "max: $max"
echo "min: $min"
========================================== #!/bin/bash # declare -i max= declare -i min= declare -i i= 1
declare -i random while [ $i -le 10 ]; do
random=$RANDOM
echo $random
if [ $i -eq 1 ]; then
max=$random
min=$max
fi
if [ $random -gt $max ]; then
max=$random
fi
if [ $random -lt $min ]; then
min=$random
fi
let i++
done echo "max: $max"
echo "min: $min"
|
本文转自 lccnx 51CTO博客,原文链接:http://blog.51cto.com/sonlich/1964037,如需转载请自行联系原作者