bash shell相关命令记录(6)---for循环、while循环

1、for循环

for循环一般格式为:

for 变量 in 列表
do
    command1
    command2
    ...
    commandN
done
列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。

in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。

举例顺序输出列表中的数字

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

顺序输出字符串

for str in 'This is a string'
do
    echo $str
done

输出结果

This is a string

 

显示 家目录下的sh文件:

for file in /home/tonglei/*.sh
do
    echo $file
done
输出结果

/home/tonglei/case.sh
/home/tonglei/echo.sh
/home/tonglei/for.sh
/home/tonglei/guanxi.sh
/home/tonglei/iffi.sh
/home/tonglei/person.sh
/home/tonglei/shuzu.sh
/home/tonglei/suanshu.sh
/home/tonglei/test.sh
/home/tonglei/tihuan.sh
/home/tonglei/zhuanyi.sh
/home/tonglei/zifucuan.sh

 

2、while 循环

while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为:

while command
do
   Statement(s) to be executed if command is true
done

命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。

举例

he=0
while [ $he -lt 5 ]
do
        he=`expr $he + 1`  --->注意是反引号
        echo $he
done

执行结果为

1
2
3
4
5

while循环可用于读取键盘信息。下面的例子中,输入信息被设置为变量NAME,按<Ctrl-D>结束循环。

echo 'type ctrl and D to stop'
echo -n "enter you name:"
while read name
do
    echo "hello,$name"
done

参考自http://c.biancheng.net/cpp/view/7008.html

猜你喜欢

转载自www.cnblogs.com/chxmtl/p/12566133.html