SHELL语法 循环

Bash Shell中主要提供了三种循环方式:for、while和until。

1. for 结构

语法结构:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

变形:
for var in item1 item2 ... itemN; do command1; command2… done;

for (( ; ; ))
do
...
done

 for循环的运行flow:是将行1 中的各串行的itemx依次取出,放入指定的变量var中,然后重复do和done之间的commandx,直到所有元素取尽为止。

example

#!/bin/bash
# description : 列出/var 目录下的所有子目录的size
DIR="/var"
cd $DIR

for i in $(ls $DIR)
do
  [ -d $i ] && du -sh $i
done

2.while循环

语法结构:

while condition
do
    command
done

无限循环变形:
while :
do
    command
done
或
while true
do
    command
done

while循环的运行flow:首先进行条件测试,如果condition为真,则进入循环执行command,否则不进入循环。

example

example1 :

#!/bin/bash
#description:将i从1到5列印
int=1
while(( $int<=5 ))
do
    echo $int
    #  Bash let 命令,执行“表达式”,引用变量时不需要加上$
    let "int++"
done


example2 :

#!/bin/bash
#description: 列印test_file 文件
while read line
do
  echo ${line}
done < /tmp/test_file

3.until循环

 

语法结构:

until condition
do
 command
done

until 循环的运行flow : 首先进行条件测试,如果condition为,则进入循环执行command,直到condition为真退出循环。

example

#!/bin/bash
#description: 将i从0到9列印

a=0

until [ ! $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值