C/C++中的while循环
int i = 0;
while (i < num)
{
//do something
}
优点:逻辑比较清晰,使用括号进行分割。
shell中的while循环
1. 第一种方式
#!/bin/bash
#author by dhy
i=0
while [ $i -lt 10 ]
do
echo "now the i is $i"
((i++))
done
- 使用中括号的方式进行逻辑判断,使用-lt 参数进行判断,符合shell中if中的判断方式
- 使用时,需要注意while 和 中括号之间和内部的空格
- do 和 done 之间需要些逻辑语句,需要进行参数i的操作,以便于跳出循环。
2. 第二种方式
可以使用两个小括号进行判断的包含。
#!/bin/bash
#author by dhy
i=0
while(($i<10))
do
echo "now the i is $i"
((i++))
done
依旧可以得到正确答案。
例:如果按照行进行循环读取文件信息
list 文件内容如下
my name is dhy
i like cpp and shell
so i prefore cpp
day day up
shell代码如下
#!/bin/bash
#author by dhy
i=0
while read line
do
echo "this $i line is $line"
((i++))
done < list.txt
运行结果:能够正确读出每行信息,并且进行处理