linux 系统中的 for 循环结构

1、基本结构

#!/bin/bash   ## 声明脚本解释器
for 变量 in 可迭代对象
do
循环体
done

2、简单实例

[root@linuxprobe test3]# for i in 1 10 100 500;do echo $i;done  ## 可以直接在命令行中使用,变量前需加 $ 符号。
1
10
100
500
[root@linuxprobe test3]# ls
[root@linuxprobe test3]# for i in a b c x y z;do mkdir $i;done
[root@linuxprobe test3]# ls
a  b  c  x  y  z

3、可迭代对象可以放在文件中

[root@linuxprobe test3]# cat test.txt
abc
www
eee
ttt
[root@linuxprobe test3]# for i in `cat test.txt`;do touch $i;done  ## 注意是反引号;反引号的部分可以使用 $(命令)代替
[root@linuxprobe test3]# ls
abc  eee  test.txt  ttt  www

[root@linuxprobe test3]# for i in $(cat test.txt);do rm -f $i;done  ## 删除刚才创建的内容
[root@linuxprobe test3]# ls
test.txt

 

4、实例

  创建测试数据

[root@linuxprobe test3]# cat test.txt ## 测试数据
2 3 4
5 a 7
3 2 b
2 4 9
3 5 b
3 9 c
3 3 4
2 4 a
4 8 5
[root@linuxprobe test3]# cat a.txt  ## 计划从test.txt文件中提取所有包含a、b、c的行,
a
b
c
[root@linuxprobe test3]# for i in `cat a.txt`;do grep "$i" test.txt >> result.txt;done ## 利用for循环结构,逐个匹配字符,追加至结果文件
[root@linuxprobe test3]# cat result.txt
5 a 7
2 4 a
3 2 b
3 5 b
3 9 c
原文地址:https://www.cnblogs.com/liujiaxin2018/p/13805714.html