Shell for循环语法
for 变量 in 列表
do
command
done
**也可以写成:for var in list; do
读取列表中的值
#!/bin/bash
#basic for command
for test in Alabama BOb Tom Console
do
echo The next state is $test
done
1
2
3
4
5
6
7
执行结果:
The next state is Alabama
The next state is BOb
The next state is Tom
The next state is Console
1
2
3
4
在最后一次迭代后,$test变量的值会在shell脚本的剩余部分保持有效。它会一直保持最后一次迭代的值(除非你修改了它)。
读取列表中的复杂值
有两种解决办法:
*使用转义字符(反斜线)来将单引号转移;
*使用双引号来定义用到单引号的值。
#!/bin/bash
#basic for command
for test in I don’t think if “this’ll” work
do
echo The next state is $test
done
1
2
3
4
5
6
7
执行结果:
The next state is I
The next state is don’t
The next state is think
The next state is if
The next state is this’ll
The next state is work
1
2
3
4
5
6
*记住,for命令用空格来划分列表中的每个值。如果在单独的数据值中有空格,就必须用双引号将这些值圈起来。
从命令读取值
有两种方式可以将命令输出赋值给变量:
(1)反引号字符(`)
(2)$()格式
例如:
test=date
test=$(date)
1
2
生成列表中所需值就是使用命令的输出。
#!/bin/bash
reading values from a file
file=“states”
#for state in ps -ef | grep 'tomcat.8701' | awk '{print $2}'
for state in $(cat $file)
do
echo “visit beautiful $state”
done
1
2
3
4
5
6
7
8
9
states文件内容;
Alabama BOb
Tom Console
1
2
执行结果:
visit beautiful Alabama
visit beautiful BOb
visit beautiful Tom
visit beautiful Console