for 循环

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值