Linux shell脚本详解及实战(三)——shell脚本循环

今天继续给大家介绍Linux基础知识,本文主要内容是Linux Shell脚本中循环相关内容。

一、shell循环——for循环

循环主要是为了重复执行一些命令,在Linux shell基本h编写中,支持for循环和while循环两种方式。
for循环格式如下:

for 循环初始条件
do
	循环体
done

循环条件可以类似C语言的风格,如:

for (i=1;i<=100;i++)

或者使用in表达式,如:

for i in `seq 100` 
for i in 1 2 3 4 5
for i in {1..10..2}
for i in `ls`

二、shell循环——while循环

while循环也是shell脚本中常用的循环方式,while循环格式如下所示:

while 表达式
do
    循环体
done

while循环体常用表达式如下所示:

while ((i<=100))
while [ $i -le 100 ]

三、shell循环——循环控制语句

Linux的shell脚本中有类似C语言风格的循环控制语句,在循环中,break命令可以跳出当前循环,而continue则可以跳转到下一次循环开始的地方。break和continue的引入使得脚本的循环代码更加灵活。

四、shell循环——循环示例

最后,给大家附几个简单的循环示例:
1、计算1+2+3+……+100的和

#!/bin/bash
# 2021-10-15
# Authored by pzz
# Used to practise shell 
i=1
count=0
while [ $i -le 100 ]
do
    count=`expr $count + $i`
    i=`expr $i + 1`
done
echo $count

2、压缩/root文件夹下文件

#!/bin/bash
# 2021-10-15
# Authored by pzz
# Used to tar /root
for i in `ls /root`
do
    tar -czf compress.tar.gz $i
done

原创不易,转载请说明出处:https://blog.csdn.net/weixin_40228200


版权声明:本文为weixin_40228200原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。