bash while循环和until循环

bash while循环和until循环

在bash中,我们除了可以使用for循环,也可以使用while循环和until循环去实现我们需要的功能;这里我总结了while和until循环相关的用法。

while循环

while循环格式如下

while 测试条件;do
    语句1
    语句2
    ...
done

示例:计算100以内所有正整数的和

[root@node1 bash_test]# cat while.sh 
#!/bin/bash

Sum=0
Count=1
while [ $Count -le 100 ];do
    let Sum+=$Count
    let ++Count
done
echo "sum of 1 to 100 : $Sum"
[root@node1 bash_test]# ./while.sh 
sum of 1 to 100 : 5050

注意:

  1. while循环体可以用命令;[];[[]] 三种形式
    括号内的表达式要有空格[空格$Count -le 100空格]
    表达式判断大小应该使用:小于-lt ,大于gt, 等于eq, 小于等于le, 大于等于ge, 不等于ne
  2. 自增可以使用let ++Count,同时也可以使用Count=$[$Count+1]
    同时let Sum+=$Count可以替换为Sum=$[$Sum+$Count]
  3. let可以限时表达式做算数运算,而不是字符运算

until循环

until循环格式如下

until 测试条件; do
    语句1
    语句2
    ....
done

示例:计算100以内所有偶数的和

[root@node1 bash_test]# cat EvenSum.sh 
#!/bin/bash

Sum=0
Count=0
until [ $Count -gt 100 ];do
    Count=$[$Count+2] 
    Sum=$[$Sum+$Count]
done
echo "Sum of all even number from 0 to 100 :$Sum"
[root@node1 bash_test]# ./EvenSum.sh 
Sum of all even number from 0 to 100 :2652

总结

  • while和until循环都是用于在事先不知道循环次数的情况下使用,for循环经常用于已知循环次数的情况下
  • while循环:当条件满足时,执行循环;不满足条件时,退出循环
  • until循环:当不满足条件时,执行循环;满足条件,就退出循环

更多示例

  1. 如果用户的ID号为偶数时,显示其名称和shell;对所有用户执行此操作
[root@node1 bash_test]# cat showEvenUser.sh 
#!/bin/bash

while read Line;do
  UserId=`echo $Line | cut -d: -f3`
  if [ $[$UserId%2] -eq 0 ];then 
      echo $Line | cut -d: -f1,7
  fi
done < /etc/passwd
[root@node1 bash_test]# ./showEvenUser.sh 
root:/bin/bash
daemon:/sbin/nologin

注意:while 循环可以接受文件路径,读取文件中每一行

while read Line;do
    语句1
    语句2
    ...
done < /path/to/somefile

2.转换用户输入的字符为大写,除了quit(遇见quit退出)

[root@node1 bash_test]# cat toUpper.sh 
#!/bin/bash

read -p "input you string(quit is quitting):" content
until [ "$content" == "quit" ];do
    echo $content | tr 'a-z' 'A-Z'
    read -p "input you string(quit is quitting):" content
done
[root@node1 bash_test]# ./toUpper.sh 
input you string(quit is quitting):apple
APPLE
input you string(quit is quitting):hello world
HELLO WORLD
input you string(quit is quitting):quit

注意:字符串变量在做比较时,最好包裹在双引号中

3.每隔5秒查看hadoop用户是否登录,如果登录,则显示登录并退出;否则,显示当前时间,并说明hadoop尚未登录

[root@node1 bash_test]# cat ./checkUser.sh 
#!/bin/bash

until who | grep "^hadoop" &> /dev/null;do
    date 
    sleep 5
    echo "hadoop not login"
done
echo "hadoop is here"
[root@node1 bash_test]# ./checkUser.sh 
2022年 07月 29日 星期五 20:59:36 CST
hadoop not login
2022年 07月 29日 星期五 20:59:41 CST
hadoop not login
hadoop is here
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值