1. 循环
1.1 不定循环
1.1.1 while
当条件为真时就进行循环,条件不成立时退出
提示用户输入“y”或“Y”来终止程序。
-a 用在判断式中表示"&&"(and)
while [ "$aa" != "y" -a "$aa" != "Y" ]
do
read -p "please input y/Y to stop this program: " aa
done
1.1.2 until
当条件成立时就终止循环,否则持续循环
提示用户输入“y”或“Y”来终止程序。
-o 用在判断式中表示"||"(or)
until [ "$aa" == "y" -o "$aa" == "Y" ]
do
read -p "please input y/Y to stop this program: " aa
done
1.2 固定循环 for
1.2.1 100以内数字求和
N=100
sum=0
for ((i=1; i<=$N; i++))
do
sum=$(($sum+$i))
done
echo "$sum"
1.2.2 循环文件中的内容(按行)
dt_file="dt.txt"
for line in $(cat $dt_file)
# cat ${dt_file} | while read line
do
echo "$line"
# local dt=$(echo ${line} | awk '{print $1}')
done
1.2.3 日期循环
#!/bin/bash
for day in `echo 2021-07-{11..21}`
# for day in `echo {0..100}`
do
echo ${day}
done
调用
bash -x aa.sh 2>/dev/null
2. case选择
实现一个脚本,判断变量是否为“hello”或“world”。
function my_print(){
echo "=^_^=: $1"
}
aa="world"
case $aa in
"hello")
my_print "is hello"
;;
"world")
my_print "is world"
;;
*)
my_print "is other"
;;
esac
备注:每个case 类型结尾使用“;;”来处理
本文介绍了Shell脚本中的循环结构,包括while和until循环的使用,以及for循环在数字求和、遍历文件内容和日期循环中的应用。同时,文章还展示了如何通过case选择结构来判断输入字符串是否匹配预设的条件。示例代码详细解释了各个结构的工作原理,是学习Shell脚本控制流程的重要参考资料。
33万+

被折叠的 条评论
为什么被折叠?



