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
[root@localhost ~]# ./test4.sh
Have you ever visited a?
Have you ever visited b?
Have you ever visited c?
Have you ever visited d?
4.读取命令中的值
生成列表中使用的另一个方法是使用命令输出,可以使用反引号字符来执行生成输出的任何命令,然后在for命令中使用命令输出:
新建一个states文件,并且添加数据内容
[root@localhost ~]# cat states
ak
bn
cd
dr
#!/bin/bash
file="states"
for state in `cat $file`
do
echo "Visit beautiful $state"
done
[root@localhost ~]# ./test5.sh
Visit beautiful ak
Visit beautiful bn
Visit beautiful cd
Visit beautiful dr
5.改变字段分隔符
内部字段分隔符(IFS),bash shell将以下字符看作是字段分隔符
空格
制表符
换行符
#!/bin/bash
file="states"
IFS=$'\n'
for state in `cat $file`
do
echo "Visit beautiful $state"
done
IFS=$'\n'通知bash shell在数值中忽略空格和制表符
6.使用通配符读取目录
#!/bin/bash
for file in /home/l*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
fi
done
[root@localhost ~]# ./test6.sh
/home/ley is a directory
for命令失代/home/ley列表的结果,然后用test命令查看是目录(-d)还是文件(-f)