> 文章列表 > shell结构化命令中for命令

shell结构化命令中for命令

shell结构化命令中for命令

for var in list
docommands
done

读取列表中的值

每次遍历值列表时,for命令会将列表中的下一个值赋值给变量

 #!/bin/bash# basic for commandfor test in Alabama Alaska Arizona Arkansas California Coloradodoecho The next state is $testdone

shell结构化命令中for命令
在最后一次迭代结束后,变量的值在shell脚本的剩余部分依然有效,会一直保留最后一次迭代时的值,当然可以修改

#!/bin/bash
# testing the for variable after the looping
for test in Alabama Alaska Arizona Arkansas California Colorado
doecho "The next state is $test"
done
echo "The last state we visited was $test"
test=Connecticut
echo "Wait, now we're visiting $test"

shell结构化命令中for命令

读取列表中的复杂值

单词中包含了单引号会导致一团糟,比如this’ll,此时要么使用转义字符来转义单引号,要么使用双引号来定义含有单引号的值

#!/bin/bash
# another example of how not to use the for commandfor test in I don\\'t know if "this'll" work
doecho "word:$test"
done

shell结构化命令中for命令
for命令默认使用空格来划分列表中的值,如果某个值包含有空格,则必须将其放到双引号内

 #!/bin/bash# an example of how to properly define valuesfor test in Nevada "New Hampshire" "New Mexico" "New York"doecho "Now going to $test"done

shell结构化命令中for命令

从变量中读取值列表

可以将值列表保存到变量中,然后进行拼接操作,再通过for命令读取

#!/bin/bash
# using a variable to hold the listlist="Alabama Alaska Arizona Arkansas Colorado"
list=$list" Connecticut"for state in $list
doecho "Have you ever visited $state?"
done

shell结构化命令中for命令

从命令中读取值列表

使用命令替换来执行任何能产生输出的命令,然后使用for命令使用该命令的输出

#!/bin/bash
# reading values from a filefile="states"for state in $(cat $file)
doecho "Visit beautiful $state"
done

shell结构化命令中for命令

更改字段分隔符

默认的字段分隔符由特殊的环境变量IFS(internal field separator 内部字段分隔符)来确定。默认值为空格、制表符、换行符(IFS=$’ \\t\\n’)
shell结构化命令中for命令
可以修改IFS的值,如果要制定多个IFS字符,则只需在赋值语句中将这些字符写在一起即可

IFS=: # 将冒号设置为字段分隔符
IFS=$' \\n:;"'  # 将换行符、冒号、分号和双引号作为字段分隔符

修改IFS的值,需要注意恢复原来的值,保证安全

IFSOLD=$IFS
IFS=:

结束时替换回去

IFS=$IFSOLD

shell结构化命令中for命令

使用通配符读取目录

可以使用for命令来自动遍历目录中的文件,但是必须在文件名和路径名中使用通配符,这会强制文件名通配符匹配(file globbing)。文件名通配符是生成与指定通配符匹配的文件名或路径名的过程。

遍历的对象可以是多个文件名通配符

#!/bin/bash
# iterating through multiple directoriesfor file in /home/rich/.b* /home/rich/badtest
doif [ -d "$file" ]thenecho "$file is a directory"elif [ -f "$file" ]thenecho "$file is a file"elseecho "$file doesn't exist"fi
done

shell结构化命令中for命令