Linux命令之for
bash shell提供了for命令,用于创建通过一系列值重复的循环。每次重复使用系列中的一个值执行一个定义的命令集。
for命令基本格式为:
for var in list
do
commands
done
1.读取列表中的值
#!/bin/bash
#basic for command
for test in a b c d e f
do
echo The next state is $test
done
每次for命令通过提供的值列表进行矢代时,它将列表中想下个值赋值给变量
[root@localhost ~]# ./test1.sh
The next state is a
The next state is b
The next state is c
The next state is d
The next state is e
The next state is f
2.读取列表中的复杂值
#!/bin/bash
for test in i don\'t know
do
echo "Word:$test"
done
注意:分号(')这里需要加斜杠(\)进行转义
[root@localhost ~]# ./test2.sh
Word:i
Word:don't
Word:know
3.从变量读取列表
#!/bin/bash
list="a b c d "
for state in $list
do
echo "Have you ever visited $state?"
done