07 循环

7.1 for

for的命令使用

[root@centos74 test]$ help for
for: for NAME [in WORDS ... ] ; do COMMANDS; done
for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done

bash风格:

#!/bin/bash
declare -i sum=0
for i in `seq 1 10` ; do
    sum+=$i
done
echo $sum

Attention

这个方案是bash风格的for语句,变量的引用都要使用$的。

c风格:

#!/bin/bash
declare -i sum=0
for ((i=0; i<=10; i++)); do
    sum+=i
done
echo $sum

Attention

这个风格是c语句风格的,变量不需要$的。

7.2 while

while的命令使用

[root@centos74 test]$ help while
while: while COMMANDS; do COMMANDS; done

样例1:

#!/bin/bash
declare -i sum=0
declare -i i=0
while [ $i -le 10 ]  ; do
        sum+=$i
        i=$[i+1]
done
echo $sum

样例2:

[root@centos74 test]$ vim person.txt
[root@centos74 test]$ cat person.txt
zhaojiedi 23
liming 24
xiaojia 18
[root@centos74 test]$ cat while2.sh
#!/bin/bash


while read name age ; do
    echo "name is $name, age is $age"
done < person.txt
[root@centos74 test]$ bash while2.sh
name is zhaojiedi, age is 23
name is liming, age is 24
name is xiaojia, age is 18

7.3 until

until 的命令使用

[root@centos74 test]$ help until
until: until COMMANDS; do COMMANDS; done

样例:

#!/bin/bash
declare -i sum=0
declare -i i=10
until [ $i -lt 0 ]  ; do
        sum+=$i
        i=$[i-1]
done
echo $sum

Attention

while是判断条件为true才继续。而until相反。

7.4 case

case的命令使用

[root@centos74 etc]$ help case
case: case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac

样例:

[root@centos74 test]$ cat case.sh
#!/bin/bash

case $1 in

a|b|c)
    echo "you enter (a|b|c)"
    ;;
d|e|f)
    echo "you enter (d|e|f)"
    ;;
*)
    echo " other char"
    ;;
esac

调用

[root@centos74 test]$ ./case.sh 2
other char
[root@centos74 test]$ ./case.sh a
you enter (a|b|c)
[root@centos74 test]$ ./case.sh d
you enter (d|e|f)

7.5 select

select的命令使用

[root@centos74 test]$ help select
select: select NAME [in WORDS ... ;] do COMMANDS; done

样例:

select c in yes no ; do
        echo " you enter is $c"
        case $c in
                yes)
                        echo "yes";;
                no)
                        echo "no";;
                *)
                        echo "other";;
        esac
done

Attention

select是不同与case的,内置有死循环的。