1 for命令
# for:迭代循环;默认空格为分隔符 for var in list
do
commands
done
1.1 读取列表中的值
#!usr/bin/bash
for test in Hello Python Student School
do
echo The next wprd is $test
done
echo The last state is $test
#一直保持最后迭代的值,除非删除(或更改)它
1.2 读取列表中复杂的值
# 使用转义字符(反斜线),转义特殊字符
# 使用双引号定义用到的单引号(或反之)
# 默认空格为分隔符
#!usr/bin/bash
for test in I don\'t know if "this'll" work
do
echo "word: $test"
done
# 双引号创建字符串变量,并作为一个整体出现在列表中 $cat fortest01.sh
#!usr/bin/bash
for var in "the test bash shell"
do
echo word: $var
done $sh fortest01.sh
word: the test bash shell $cat fortest01.sh
#!usr/bin/bash
for var in "the test bash shell" "the last test"
do
echo word: $var
done $sh fortest01.sh
word: the test bash shell
word: the last test
1.3 从变量中读取列表
# 注意与直接读取列表的区别:
# 列表:
* 列表中特殊字符的转义字符
* 双引号-特殊字符和字符串变量(整体)
# 变量
* 定义字符串变量-双引号/单引号
* 字符串添加元素
* for迭代遍历变量元素
$cat varfortest02.sh
#!usr/bin/bash
list01='the first test example'
list02=" the second test example"
list03=$list02" the thrid test example"
list04=$list01$list02$list03
echo $list04
n=
for var in $list04
do
(( n++ ))
echo cycle $n: $var
done $sh varfortest02.sh
the first test example the second test example the second test example the thrid test example
cycle : the
cycle : first
cycle : test
cycle : example
cycle : the
cycle : second
cycle : test
cycle : example
cycle : the
cycle : second
cycle : test
cycle : example
cycle : the
cycle : thrid
cycle : test
cycle : example
1.4 从命令读取值
# 反引号
* 使用文件的绝对路径,除非位于同一个目录
* 默认空格为分隔符
$cat commandfor.sh
#!usr/bin/bash
n=
for var in `cat varfortest02.sh`
do
n=$[ $n+ ]
echo line $n: $var
done $sh commandfor.sh
line : #!usr/bin/bash
line : list01='the
line : first
... ...
line : do
line : ((
line : n++
line : ))
... ...
line : $var
line : done
1.5 更改字段分隔符
# 环境变量IFS-内部字段分隔符
* 默认分隔符:空格;制表符;换行符
* 更改:单个:IFS=$'\n'-(换行)
多个:IFS=$'\n:;"'-(换行/冒号/分号/双引号)
* 保存与恢复:
IFS.OLD=$IFS
IFS=$'\n'
...
IFS=$IFS.OLD $cat commandfor.sh
#!usr/bin/bash
n=
IFS.OLD=$IFS
IFS=$'\n'
for var in `cat varfortest02.sh`
do
n=$[ $n+ ]
echo line $n: $var
done
IFS=$IFS.OLD $sh commandfor.sh
commandfor.sh: line : IFS.OLD=: command not found
line : #!usr/bin/bash
line : list01='the first test example'
line : list02=" the second test example"
line : list03=$list02" the thrid test example"
line : list04=$list01$list02$list03
line : echo $list04
line : n=
line : for var in $list04
line : do
line : (( n++ ))
line : echo cycle $n: $var
line : done
1.6 用通配符读取文件/目录
# 文件/目录变量尽量用双引号括起来
# 文件/目录查找方法和列表方法合并进同一个for语句
* 可以添加任意多个通配符,for语句先匹配文件或目录形成列表,然后遍历列表
$cat filefor.sh
#!usr/bin/bash
for file in ./* ./tsttst
do
if [ -e "$file" ]
then
echo The file is $file
else
echo The fiel $file do not exist!
fi
done $sh filefor.sh
The file is ./commandfor.sh
The file is ./filefor.sh
The file is ./fortest01.sh
The file is ./varfortest02.sh
The fiel ./tsttst do not exist!