shell脚本编程之更多结构化命令(二)

简介: shell脚本编程之更多结构化命令(二)

6.循环处理文件数据


通常必须遍历存储在文件中的数据,这要求结合已讲过的两种技术:

a.使用嵌套循环;

b.修改IFS环境变量;


通过修改IFS环境变量,就能强制for命令将文件中的每行都当成单独的一个条目来处理,即使数据中有空格也是如此。一旦从文件中提取出了单独的行,可能需要再次利用循环来提取行中的数据。典型的案例是处理/etc/passwd文件中的数据,逐行遍历/etc/passwd文件,并将IFS变量的值改成冒号,这样就能分割开每行中的各个数据段。如下例所示:


1#!/bin/bash
 2
 3IFS.OLD=$IFS
 4
 5IFS=$'\n'
 6for var in $( cat /etc/passwd )
 7do
 8    echo "Values in $var -"
 9    IFS=:
10    for v in $var
11    do
12        echo "  $v"
13    done
14done
15
16# 结果
17[njust@njust tutorials]$ ./dana15.sh 
18Values in root:x:0:0:root:/root:/bin/bash -
19root
20x
210
220
23root
24/root
25/bin/bash


7.控制循环


7.1 break命令

break语句是退出循环的一个简单方法。可以使用break命令来退出任意类型的循环,包括while循环和until循环。跳出单个循环:在shell执行break命令时,它会尝试跳出当前正在执行的循环。


1#!/bin/bash
 2
 3for var in 1 2 3 4 5 6 7 8 9 10
 4do
 5    if [ $var -eq 5 ]
 6    then
 7        break
 8    fi
 9    echo "Current number: $var"
10done
11echo "The for loop is completed"
12
13# 结果
14[njust@njust tutorials]$ ./dana16.sh 
15Current number: 1
16Current number: 2
17Current number: 3
18Current number: 4
19The for loop is completed



跳出单个循环的情景同样也适用于while和until循环,如下例所示:



1#!/bin/bash
 2
 3var=1
 4
 5while [ $var -lt 10 ]
 6do
 7    if [ $var -eq 5 ]
 8    then
 9        break
10    fi
11    echo "Iteration: $var"
12    var=$[ $var + 1 ]
13done
14
15echo "The while loop is completed"
16
17# 结果
18[njust@njust tutorials]$ ./dana17.sh 
19Iteration: 1
20Iteration: 2
21Iteration: 3
22Iteration: 4
23The while loop is completed


跳出内部循环:在处理多个循环时,break命令会自动终止你所在的最内层的循环。


1#!/bin/bash
 2
 3for (( a =  1; a < 4; a++ ))
 4do
 5    echo "Outer loop:$a"
 6    for (( b = 1; b < 100; b++ ))
 7    do
 8        if [ $b -eq 5 ]
 9        then
10            break
11        fi
12        echo "  Inner loop:$b"
13    done
14done
15
16# 结果
17[njust@njust tutorials]$ ./dana18.sh 
18Outer loop:1
19    Inner loop:1
20    Inner loop:2
21    Inner loop:3
22    Inner loop:4
23Outer loop:2
24    Inner loop:1
25    Inner loop:2
26    Inner loop:3
27    Inner loop:4
28Outer loop:3
29    Inner loop:1
30    Inner loop:2
31    Inner loop:3
32    Inner loop:4


跳出外部循环:有时候你在内部循环,但需要停止外部循环。break命令接收

单个命令行参数值:break n。n指定了要跳出的循环层级,默认情况下,n等于1,表示跳出的是当前的循环。如果n设置为2,break命令会停止下一级的外部循环。如下例所示:


1#!/bin/bash
 2
 3for (( a = 1; a < 4; a++ ))
 4do
 5    echo "Outer loop:$a"
 6    for (( b = 1; b < 100; b++ ))
 7    do
 8        if [ $b -gt 4 ]
 9        then
10            break 2
11        fi
12        echo "  Inner loop:$b"
13    done
14done 
15
16# 结果
17[njust@njust tutorials]$ ./dana19.sh 
18Outer loop:1
19    Inner loop:1
20    Inner loop:2
21    Inner loop:3
22    Inner loop:4


7.2 continue命令


continue命令可以提前中止某次循环中的命令,但并不会完全终止整个循环。可以在循环内部设置shell不执行命令的条件。如下例所示:


1#!/bin/bash
 2
 3for (( a = 1; a < 15; a++ ))
 4do
 5    if [ $a -gt 5 ] && [ $a -lt 10 ]
 6    then
 7        continue
 8    fi
 9    echo "Iteration number: $a"
10done
11
12# 结果
13Iteration number: 1
14Iteration number: 2
15Iteration number: 3
16Iteration number: 4
17Iteration number: 5
18Iteration number: 10
19Iteration number: 11
20Iteration number: 12
21Iteration number: 13
22Iteration number: 14


也可以在while或until循环中使用continue命令,但是特别小心。当shell执行continue命令时,它会跳过剩余的命令。如果你在其中某个条件里对测试条件变量进行增值,问题就会出现。


1#!/bin/bash
 2
 3var1=0
 4
 5while echo "while iteration: $var1"
 6      [ $var1 -lt 15 ]
 7do
 8    if [ $var1 -gt 5 ] && [ $var1 -lt 10 ]
 9    then
10        continue  # 当shell执行continue命令时,它跳过了while循环中余下的命令。
11    fi
12    echo "  Inside iteration number:$var1"
13    var1=$[ $var1 + 1 ]
14done
15
16# 结果
17[njust@njust tutorials]$ ./dana21.sh 
18while iteration: 0
19Inside iteration number:0
20while iteration: 1
21Inside iteration number:1
22while iteration: 2
23Inside iteration number:2
24while iteration: 3
25Inside iteration number:3
26while iteration: 4
27Inside iteration number:4
28while iteration: 5
29Inside iteration number:5
30while iteration: 6
31while iteration: 6
32while iteration: 6
33while iteration: 6
34while iteration: 6
35while iteration: 6
36while iteration: 6
37while iteration: 6
38while iteration: 6
39while iteration: 6


和break命令类似,continue命令也允许通过命令行参数指定要继续执行哪一级循环:continue n。其中n定义了要继续的循环层级,如下例所示:


1#!/bin/bash
 2
 3for (( a = 1; a <= 5; a++ ))
 4do
 5    echo "Iteration: $a"
 6    for (( b = 1; b < 3; b++ ))
 7    do 
 8        if [ $a -gt 2 ] && [ $a -lt 4 ]
 9        then
10            continue 2 
11        fi
12        var=$[ $a * $b ]
13        echo "  The result of $a * $b is $var"
14    done
15done 
16
17# 结果
18[njust@njust tutorials]$ ./dana22.sh 
19Iteration: 1
20The result of 1 * 1 is 1
21The result of 1 * 2 is 2
22Iteration: 2
23The result of 2 * 1 is 2
24The result of 2 * 2 is 4
25Iteration: 3
26Iteration: 4
27The result of 4 * 1 is 4
28The result of 4 * 2 is 8
29Iteration: 5
30The result of 5 * 1 is 5
31The result of 5 * 2 is 10


8.处理循环的输出



在shell脚本中,可以对循环的输出使用管道或进行重定向。可以通过在done命令后添加一个处理命令来实现。如下例所示:


1#!/bin/bash
 2
 3for file in /home/njust/*
 4do
 5    if [ -d "$file" ]
 6    then
 7        echo "$file is a directory"
 8    else
 9        echo "$file is a file"
10    fi
11done > output.txt
12
13# 结果
14[njust@njust tutorials]$ cat output.txt 
15/home/njust/sentinel is a file
16/home/njust/tutorials is a directory
17/home/njust/公共 is a directory
18/home/njust/模板 is a directory
19/home/njust/视频 is a directory
20/home/njust/图片 is a directory
21/home/njust/文档 is a directory
22/home/njust/下载 is a directory
23/home/njust/音乐 is a directory
24/home/njust/桌面 is a directory


上述方法同样适用于将循环的结果通过管道传给另一个命令,如下例所示:


1#!/bin/bash
 2
 3for state in "North Dakota" Pink Blue Green Red
 4do
 5    echo "$state is the next place to go"
 6done | sort
 7
 8echo "This completes our travels"
 9
10# 结果
11[njust@njust tutorials]$ ./dana24.sh 
12Blue is the next place to go
13Green is the next place to go
14North Dakota is the next place to go
15Pink is the next place to go
16Red is the next place to go
17This completes our travels


9.循环在实际中的应用


查找可执行文件


1#!/bin/bash
 2
 3IFS=:
 4
 5for folder in $PATH
 6
 7do
 8    echo "$folder"
 9    for file in $folder/*
10    do
11        if [ -x $file ]
12        then
13            echo "  $file"
14        fi
15    done
16done
17
18# 结果
19/sbin/vgextend
20/sbin/vgimport
21/sbin/vgimportclone
22/sbin/vgmerge
23/sbin/vgmknodes
24/sbin/vgreduce
25/sbin/vgremove
26/sbin/vgrename
27/sbin/vgs
28/sbin/vgscan
29/sbin/vgsplit
30/sbin/vigr


创建多个用户账户


1#!/bin/bash
 2
 3input="users.txt"  # users.txt文件需提前创建,文件内容为:userid,username
 4
 5while IFS=',' read -r userid name
 6do
 7    echo "adding $userid"
 8    useradd -c "$name" -m $userid
 9
10done < "$input"
11
12# 结果,必须用root用户才能运行此脚本,因为useradd命令需要root权限!
13[root@njust tutorials]# ./dana26.sh
14adding C001
15adding D002
16adding H003
17adding J004
18
19# 验证
20[root@njust tutorials]# tail /etc/passwd
21postfix:x:89:89::/var/spool/postfix:/sbin/nologin
22ntp:x:38:38::/etc/ntp:/sbin/nologin
23tcpdump:x:72:72::/:/sbin/nologin
24njust:x:1000:1000:njust:/home/njust:/bin/bash
25shenchao:x:1001:1001::/home/shenchao:/bin/bash
26userid:x:1002:1003:name:/home/userid:/bin/bash
27C001:x:1003:1004:curry:/home/C001:/bin/bash
28D002:x:1004:1005:durant:/home/D002:/bin/bash
29H003:x:1005:1006:harden:/home/H003:/bin/bash
30J004:x:1006:1007:james:/home/J004:/bin/bash


10.资料下载


[1] https://github.com/cdlwhm1217096231/Linux/tree/master/Shell%E8%84%9A%E6%9C%AC%E7%BC%96%E7%A8%8B

相关文章
|
Shell
Shell脚本循环控制:shift、continue、break、exit指令
使用这些命令可以让你的Shell脚本像有生命一样动起来。正确使用它们,你的脚本就能像一场精心编排的舞蹈剧目,既有旋律的起伏,也有节奏的跳跃,最终以一场惊艳的表演结束。每一个动作、每一个转折点,都准确、优雅地完成所需要表达的逻辑。如此,你的脚本不只是冰冷的代码,它透过终端的界面,跳着有节奏的舞蹈,走进观众——使用者的心中。
544 60
|
存储 安全 Unix
七、Linux Shell 与脚本基础
别再一遍遍地敲重复的命令了,把它们写进Shell脚本,就能一键搞定。脚本本质上就是个存着一堆命令的文本文件,但要让它“活”起来,有几个关键点:文件开头最好用#!/usr/bin/env bash来指定解释器,并用chmod +x给它执行权限。执行时也有讲究:./script.sh是在一个新“房间”(子Shell)里跑,不影响你;而source script.sh是在当前“房间”里跑,适合用来加载环境变量和配置文件。
1193 9
|
存储 Shell Linux
八、Linux Shell 脚本:变量与字符串
Shell脚本里的变量就像一个个贴着标签的“箱子”。装东西(赋值)时,=两边千万不能有空格。用单引号''装进去的东西会原封不动,用双引号""则会让里面的$变量先“变身”再装箱。默认箱子只能在当前“房间”(Shell进程)用,想让隔壁房间(子进程)也能看到,就得给箱子盖个export的“出口”戳。此外,Shell还自带了$?(上条命令的成绩单)和$1(别人递进来的第一个包裹)等许多特殊箱子,非常有用。
1259 2
|
Web App开发 缓存 安全
Linux一键清理系统垃圾:释放30GB空间的Shell脚本实战​
这篇博客介绍了一个实用的Linux系统盘清理脚本,主要功能包括: 安全权限检查和旧内核清理,保留当前使用内核 7天以上日志文件清理和系统日志压缩 浏览器缓存(Chrome/Firefox)、APT缓存、临时文件清理 智能清理Snap旧版本和Docker无用数据 提供磁盘空间使用前后对比和大文件查找功能 脚本采用交互式设计确保安全性,适合定期维护开发环境、服务器和个人电脑。文章详细解析了脚本的关键功能代码,并给出了使用建议。完整脚本已开源,用户可根据需求自定义调整清理策略。
1637 1
|
数据采集 监控 Shell
无需Python:Shell脚本如何成为你的自动化爬虫引擎?
Shell脚本利用curl/wget发起请求,结合文本处理工具构建轻量级爬虫,支持并行加速、定时任务、增量抓取及分布式部署。通过随机UA、异常重试等优化提升稳定性,适用于日志监控、价格追踪等场景。相比Python,具备启动快、资源占用低的优势,适合嵌入式或老旧服务器环境,复杂任务可结合Python实现混合编程。
|
存储 Unix Shell
确定Shell脚本在操作系统中的具体位置方法。
这对于掌握Linux的文件系统组织结构和路径方面的理解很有帮助,是我们日常工作和学习中都可能使用到的知识。以上讲解详细清晰,应用简便,是每一个想要精通操作系统的计算机爱好者必备的实用技能。
2084 17
|
Linux Shell
在Linux、CentOS7中设置shell脚本开机自启动服务
以上就是在CentOS 7中设置shell脚本开机自启动服务的全部步骤。希望这个指南能帮助你更好地管理你的Linux系统。
2703 25
|
Linux Shell
Centos或Linux编写一键式Shell脚本删除用户、组指导手册
Centos或Linux编写一键式Shell脚本删除用户、组指导手册
584 4
|
Linux Shell 数据安全/隐私保护
Centos或Linux编写一键式Shell脚本创建用户、组、目录分配权限指导手册
Centos或Linux编写一键式Shell脚本创建用户、组、目录分配权限指导手册
863 3
|
存储 Unix Shell
Shell 输出命令完全指南:echo 与 printf 的深度剖析
本文深入解析了 Shell 编程中 `echo` 和 `printf` 两个核心输出命令的用法与区别。`echo` 简单易用,适合基础输出;`printf` 功能强大,支持复杂格式化。文章从语法、转义序列、高级技巧到实际应用场景(如日志记录、进度显示)逐一讲解,并对比两者的性能与适用场景,帮助开发者根据需求灵活选择。最后通过进阶技巧和常见问题解答,进一步提升对两者的掌握程度。
1143 1