三、更多结构化命令
前面已经讲述了检查命令的输出和变量的值来操作shell脚本程序中的流。如下主要说明如何执行重复的过程和命令,使得一组命令循环下去,直到满足特定的条件。
知识内容:
# 使用for语句循环
# 使用until语句迭代
# 使用while语句
# 结合循环
# 重定向循环输出
1、for命令
重复一系列的命令是常见的编程实践,对于shell如处理目录下的所有文件、系统中的所有用户、或者文本文件中的所有行。对于bash shell的for循环命令格式:
for xxx in xx
do
command
done
在xx参数里头提供一系列用户迭代的值,如下例:
1.1、读取列表中的值
[root@wzp ~]# cat test3
#!/bin/bash
for test in CCNA CCNP RHCE OCP OCM
do
echo the learning list is $test
done
[root@wzp ~]# ./test3
the learning list is CCNA
the learning list is CCNP
the learning list is RHCE
the learning list is OCP
the learning list is OCM
上面的结果应该很好理解,有点还要说明的是迭代的最后一个值仍然有效,我可以通过在done后面重新显示出来,当然也可以再次修改它:
[root@wzp ~]# cat test3
#!/bin/bash
for test in CCNA CCNP RHCE OCP OCM
do
echo the learning list is $test
done
echo the last list is $test
test='good job'
echo but the last point is $test
[root@wzp ~]# ./test3
the learning list is CCNA
the learning list is CCNP
the learning list is RHCE
the learning list is OCP
the learning list is OCM
the last list is OCM
but the last point is good job
可以看到最后的迭代值是OCM,重新赋值可以被修改的!
1.2、读取列表中的复杂值
如果列表中出现一些单引号,可以通过转义符号(反斜杠符号)或者双引号来定义单引号的值;还有就是如果要处理空格问题,可以通过双引号括起来,实现最终效果,如下例:
[root@wzp ~]# cat test3
#!/bin/bash
for cities in guang zhou shang hai bei jing
do
echo my favorite city is $cities
done
[root@wzp ~]# ./test3
my favorite city is guang
my favorite city is zhou
my favorite city is shang
my favorite city is hai
my favorite city is bei
my favorite city is jing
很明显,这不是我要的结果,城市都被乱切了~
所以可以通过灵活使用双引号解决,如下:
[root@wzp ~]# cat test3
#!/bin/bash
for cities in "guang zhou" "shang hai" "bei jing"
do
echo my favorite city is $cities
done
[root@wzp ~]# ./test3
my favorite city is guang zhou
my favorite city is shang hai
my favorite city is bei jing
1.3、读取命令中的值
生成in后面这个列表的值可以通过使用命令的输出,但这里需要协助`这个少见但是shell中常用的反引号!看下例子:
[root@wzp ~]# cat somefile
aa
bb
cc
dd
首先查看somefile这个文本文件内容
[root@wzp ~]# cat test3
#!/bin/bash
file=somefile
for words in `cat $file`
do
echo the word is $words
done
[root@wzp ~]# ./test3
the word is aa
the word is bb
the word is cc
the word is dd
执行后可以理解到,列表时调用了somefile文件的每一行,注意somefile所处的位置是shell脚本中可以调用的,不然必须使用绝对路径或相对路径了。
这里我故意把somefile文件mv到别的地方去,结果执行文件是报错:
[root@wzp ~]# ./test3
cat: somefile: 没有那个文件或目录
1.4、使用通配符读取目录
文件通配是生产与指定通配符匹配的文件或者路径名的过程,如下例:
[root@wzp test]# pwd
/root/test
[root@wzp test]# touch aa bb cc
[root@wzp test]# mkdir dd ee ff
先创建三个文件格三个目录
[root@wzp ~]# cat test3
#!/bin/bash
for file in $HOME/test/*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
fi
done
[root@wzp ~]# ./test3
/root/test/aa is a file
/root/test/bb is a file
/root/test/cc is a file
/root/test/dd is a directory
/root/test/ee is a directory
/root/test/ff is a directory
通过if-then即可判断通配符*下的类型了~~