一、for 命令的语法
方式一:
for var in list
do
commands
done
方式二:
for var in list;do
commands
done
二、使用方法
1.读取列表中的值
#!/bin/bash
for test in shanghai beijing anhui nanjin tianjin "New York"
do
echo the city is $test
done
echo "最后一个字段是test="$test
test=hellowrod
echo "重新赋值后的数据test="$test
执行结果
~/test_shell_script $ ./test_for_easylist.sh
the city is shanghai
the city is beijing
the city is anhui
the city is nanjin
the city is tianjin
the city is New York
最后一个字段是test=New York
重新赋值后的数据test=$
字段值中带有空格的,尽量使用双引号标注,避免问题发生
2.读取复杂列表中的值
读取的列表中带有单引号('
)
#!/bin/bash
for test in I don't know if this'll word
do
echo word:$test
done
执行结果
word:I
word:dont know if thisll
word:word
两种解决方案:
- 使用转义字符(反斜杠
\
)来将单引号转义处理 - 使用双引号来定义含有单引号的值
for test in I don\'t know if "this'll" word
do
echo word:$test
done
执行结果
word:I
word:don't
word:know
word:if
word:this'll
word:word
3.读取变量列表中的值
list="shanghai beijing anhui nanjin tianjin"
list=$list" yunnan"
for test in $list
do
echo the city is: $test
done
执行结果
the city is: shanghai
the city is: beijing
the city is: anhui
the city is: nanjin
the city is: tianjin
the city is: yunnan
? 假设 list 中有 New York这种带有空格的字段呢?
4.读取文件列表中的值
准备一个 demo.txt 文件
anhui
tianjin
案例脚本:
list="demo.txt"
for test in $(cat $list)
do
echo the city is: $test
done
执行结果
the city is: anhui
the city is: tianjin
5.更改字段分隔符
IFS,即内部字段分隔符,定义了 bash shell 用作字段分隔符的一系列操作,在默认的情况下会将以下三种情况视作字段分隔符:
- 空格
- 制表位
- 换行符
创建一个demo2.txt 文件,New York
中间有空格,New1:York1
中间有冒号
tianjin
New York
New1:York1
执行结果:
the city is: tianjin
the city is: New
the city is: York
the city is: New1:York1
我们发现New York
被分割输出了,这并不是我想要的结果。
这是为什么?造成这个问题的原因是特殊的环境变量IFS
,默认的字段分割符导致。
增加IFS=$'\n:'
设置,表示以换行符和冒号作为分割符
IFS=$'\n:'
list="demo.txt"
for test in $(cat $list)
do
echo the city is: $test
done
执行结果:
the city is: tianjin
the city is: New York
the city is: New1
the city is: York1
6.使用通配符读取目录
案例脚本:
for test in /Users/zhangsan/test_shell_script/*
do
if [ -d "$test" ]; then
echo 这是个文件夹:$test
fi
if [ -f "$test" ]; then
echo 这是个文件:$test
fi
done
执行结果:
这是个文件:/Users/zhangsan/test_shell_script/a.txt
这是个文件夹:/Users/zhangsan/test_shell_script/data
这是个文件:/Users/zhangsan/test_shell_script/demo.txt