shell脚本允许您从各种循环结构中进行选择。 以下是常用的循环结构及其用法:
1。 对于循环
,用于循环,用于遍历列表或范围。
转移列表#! /bin/bash
用于苹果香蕉樱桃
do echo“ item:$ item”
完成
h]
array
#! /bin/bash
fruits =(“苹果”“香蕉”“”“樱桃”)
” $ {fruits
[ h]
@]}“
做
echo“水果:$ crual”
传输号码范围
#!/bin/bash
] {1。 >循环反复执行代码
基本使用#! “ count:$ count”
((count ++))
完成
文件描述符
#!/bin/bash
exec 3 <file.txt
读取行使用<&3
do
echo“ line:$ line”
完成
exec3
如果条件为false,请重复执行代码块,直到循环类似于时间循环为止。
#! /bin/bash
count = 1
[$ count -gt 5]
Echo“ count:$ count”
((count ++))
4。 选择循环
使用选择循环从一组选项中选择一个。
#! /bin/bash
options =(“苹果”“香蕉”“樱桃”“ exit”)
选择opt in in $ {options [@]}”
do
case $ opt
“苹果”)
echo“选择苹果”
;;
“香蕉”)
Echo“您选择了香蕉” 樱桃”)
回声“你选择樱桃”
; echo“无效的选项” ;; ESAC 5。 案例语句
案例语句不是循环结构,而是与循环结合使用以处理多种条件。
#! /bin/bash
读-p“ number(1-3):“ num
case $ num in
1)
1)
echo“ 1 inputted”
;
*)
回声“无效号码”
;; $ {array [@]}数组的元素。
确保条件变量在循环的主体内更新,以避免无限循环,直到ullops。
使用断路语句尽早终止循环。
使用继续语句跳过当前的迭代并继续进行下一个迭代。
这些环结构对运行Shell脚本的过程提供了灵活的控制。
评论前必须登录!
注册