shell编程学习笔记(十一):Shell中的while/until循环

shell中也能够实现相似java的while循环java

 

while循环是指知足条件时,进行循环shell

示例:函数

1 #! /bin/sh
2 index=10
3 while [ $index -gt 0 ]
4 do
5 index=$((index-1));
6 echo $index
7 done

while循环以whille开始,循环体以do开始,以done结束spa

注意第5行的代码,表达式index-1外面添加了$(()),若是不添加$(())的话,会报错,由于这里index是字符串,获得的结果不是9,而是10-1code

第5行的index-1也能够写成--index,这个跟java语言一致。blog

 

我把上面的代码稍作修改:字符串

#! /bin/sh
index=0
while [ $index -gt 0 ]
do
index=$((index-1));
echo $index
done

执行这段代码并不会输入任何内容,说明必须知足条件才会执行,不存在循环第1条时一定会执行的状况class

 

为了运算index-1,上面使用了$(()),否则只会当字符串来处理,固然了,能够使用declare -i index=10直接把index声明为总体:变量

#! /bin/sh
declare -i index=10
while [ $index -gt 0 ]
do
index=index-1;
echo $index
done

 

declare的参数声明:循环

  • +/-  "-"可用来指定变量的属性,"+"则是取消变量所设的属性。
  • -f  仅显示函数。
  • r  将变量设置为只读。
  • x  指定的变量会成为环境变量,可供shell之外的程序来使用。
  • i  [设置值]能够是数值,字符串或运算式。

 

until循环恰好跟while循环相反,是指不知足条件时,进行循环

 

示例:

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

以上示例执行时,会从10开始循环输出,输出到0,结束。

相关文章
相关标签/搜索