# shell
循环语句for
命令
bash shell
中 for
命令的基本格式:
for var in list
do
commands
done
list
参数中,需要提供迭代中要用到的一系列值。指定列表中值的方法:
# 读取列表中的值
#!/bin/bash
for v in a b c; do
echo "The Text is $v"
done
# The Text is a
# The Text is b
# The Text is c
# 读取列表中的复杂值
当列表中包含单引号时会导致迭代出错:
#!/bin/bash
for v in I can't argee that's right ; do
echo "The word is $v"
done
# The word is I
# The word is cant argee thats
# The word is right
可以看到因为受单引号的影响并没有按word by word
输出。解决办法有两个,
- 对单引号进行转义
- 使用双引号包围
#!/bin/bash
for v in I can\'t argee "that's" right ; do
echo "The word is $v"
done
# The word is I
# The word is can't
# The word is argee
# The word is that's
# The word is right
for
命令用空格来划分列表中的每个值。如果在单独的数据值中有空格,就必须用双引号将这些值圈起来。
#!/bin/bash
for v in a "b c" ; do
echo "The word is $v"
done
# The word is a
# The word is b c
# 从变量读取列表
将一系列值都集中存储在了一个变量中,然后需要遍历变量中的整个列表。
#!/bin/bash
ll="a b c"
ll=$ll" dd"
for s in $ll
do
echo "char $s"
done
# char a
# char b
# char c
# char dd
# 迭代数组
前面介绍过数组的定义,这里使用for
循环在bash shell
中使用array
的方式如下:
#!/bin/bash
arr=(1 2 3)
for i in ${arr[@]}; do
echo $i
done
# 1
# 2
# 3
${array[@]}
是取数组中的所有值。
# 从命令读取值
生成列表中所需值的另外一个途径就是使用命令的输出。
#!/bin/bash
# content of file
# a bbb
# b
# cc
# ddd
file=file
for v in $(cat $file)
do
echo "value from file $v"
done
# value from file a
# value from file bbb
# value from file b
# value from file cc
# value from file ddd
设置for命令分割符,bash shell
中默认的分割符是空格/制表符/换行符
,这是由特殊的环境变量 IFS
(internal field separator),也被称为内部字段分隔符。
要解决这个问题,可以在shell
脚本中临时更改 IFS
环境变量的值来限制被bash shell
当作字段分隔符的字符。例如,如果修改 IFS
的值,使其只能识别换行符,那就必须这么做:
IFS=$'\n'
#!/bin/bash
# content of file
# a bbb
# b
# cc
# ddd
IFS=$'\n'
file=file
for v in $(cat $file)
do
echo "value from file $v"
done
# value from file a bbb
# value from file b
# value from file cc
# value from file ddd
如果要指定多个 IFS
字符,只要将它们在赋值行串起来就行。
IFS=$'\n':;"
# 用通配符读取目录
可以用 for 命令来自动遍历目录中的文件。进行此操作时,必须在文件名或路径名中
使用通配符。它会强制shell使用文件扩展匹配。文件扩展匹配是生成匹配指定通配符的文件名或
路径名的过程。
#!/bin/bash
for file in /home/rob/* /home/rich/badtest
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
else
echo "$file doesn't exist"
fi
done
# /home/rob/模板 is a directory
# /home/rob/file is a file
# /home/rob/test1 is a file
# /home/rob/test2 is a file
# /home/rob/test.sh is a file
# /home/rich/badtest doesn't exist
# C
语言风格的shell for
循环
shell
还可以支持类似C
语言的for
循环,变量和等号之间可以有空格,访问变量的值不需要$
符号。但这会造成shell
程序编写人员的困惑,减少使用。
#!\bin\bash
for (( i=1; i <= 5; i++))
do
echo "The next number is $i"
done
# The next number is 1
# The next number is 2
# The next number is 3
# The next number is 4
# The next number is 5