运维(11)- shell循环

简介: 运维(11)- shell循环

for/do/done

Shell脚本的for循环结构和C语言很不一样,它类似于某些编程语言的foreach循环。例如:

#! /bin/sh
    for FRUIT in apple banana pear; do
      echo "I like $FRUIT"
    done

FRUIT是一个循环变量,第一次循环$FRUIT的取值是apple,第二次取值是banana,第三次取值是pear。再比如,要将当前目录下的chap0、chap1、chap2等文件名改为chap0~chap1~chap2~等(按惯例,末尾有~字符的文件名表示临时文件),这个命令可以这样写:

$ for FILENAME in chap?; do mv $FILENAME $FILENAME~; done

也可以这样写:

$ for FILENAME in `ls chap?`; do mv $FILENAME $FILENAME~; done

while/do/done

while的用法和C语言类似。比如一个验证密码的脚本:

#! /bin/sh
    echo "Enter password:"
    read TRY
    while [ "$TRY" != "secret" ]; do
      echo "Sorry, try again"
      read TRY
    done

下面的例子通过算术运算控制循环的次数:

#! /bin/sh
    COUNTER=1
    while [ "$COUNTER" -lt 10 ]; do
      echo "Here we go again"
      COUNTER=$(($COUNTER+1))
    done

break和continue

break[n]可以指定跳出几层循环,continue跳过本次循环步,没跳出整个循环。

break跳出,continue跳过。

目录
相关文章
|
4天前
|
存储 运维 Shell
shell中for while until 三种循环的用法
shell编程中,有几种常见的循环结构,包括for循环、while循环和until循环,总的来说,循环shell编程中扮演着至关重要的角色,它们使得自动化任务变得更加容易,提高了效率,并且可以处理各种各样的编程需求。
257 13
shell中for while until 三种循环的用法
|
4天前
|
Shell
在Shell脚本中,`for`循环
在Shell脚本中,`for`循环
31 2
|
4天前
|
监控 Shell
shell学习(五) 【循环控制continue,break、while 语法】
shell学习(五) 【循环控制continue,break、while 语法】
13 0
|
6月前
|
运维 Shell 测试技术
运维(23)- shell自动化部署
运维(23)- shell自动化部署
45 0
|
4天前
|
Shell
shell脚本for循环复杂用法
shell脚本for循环复杂用法
51 5
|
4天前
|
算法 Shell Linux
Linux的shell命令——判断与循环
Linux的shell命令——判断与循环
45 1
|
4天前
|
存储 运维 Shell
Shell内置命令大全,Linux运维工程师收藏!
Shell内置命令大全,Linux运维工程师收藏!
174 0
Shell内置命令大全,Linux运维工程师收藏!
|
4天前
|
运维 Linux 网络安全
利用群晖NAS+shell脚本实现运维命令执行结果文件自动上传
利用群晖NAS+shell脚本实现运维命令执行结果文件自动上传
147 0
|
4天前
|
Shell
在Shell(如Bash)中,`while`循环
在Shell(如Bash)中,`while`循环
49 2
|
5月前
|
Shell
shell的for循环使用
shell的for循环使用
25 0