for
2024年06月27日
一、认识
Shell
支持for
循环。
二、语法
2.1 for value in ${array[@]}
#!/usr/bin/env bash
array=({item1..itemN})
// 或者
array=$(seq itemm1 itemN)
// 或者
array=(item1 item2 item3 …… itemN)
for file in ${array[@]}
do
command1
command2
...
commandN
done
2.2 for value in {item1..itemN}; do done
for value in {item1..itemN};
do
command1
command2
...
commandN
done
for value in {item1..itemN}; do done
使用大括号扩展(Brace Expansion
)的方法, 这样可以避免使用子进程来调用 seq
命令,使脚本更高效和直观。
2.2 for value in $(seq item1 itemN); do done
for value in $(seq item1 itemN);
do
command1
command2
...
commandN
done
for value in $(seq item1 itemN); do done
使用 seq
命令来生成序列
2.4 for value in item1 item2 ... itemN do done
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
三、用法
3.1 循环输出
for value in {item1..itemN}; do done
方式
#!/usr/bin/env bash
for value in {1..5};
do
a=${value}
b=${value+1}
echo "a = ${a}, b = ${b}"
done
# 通过 sh test.sh 执行脚本
for value in $(seq item1 itemN); do done
方式
#!/usr/bin/env bash
for value in $(seq 1 5);
do
a=${value}
b=${value+1}
echo "a = ${a}, b = ${b}"
done
for value in item1 item2 ... itemN do done
方式
#!/usr/bin/env bash
for value in 1 2 3 4 5;
do
a=${value}
b=${value+1}
echo "a = ${a}, b = ${b}"
done
3.2 批量写入文件
#!/usr/bin/env bash
fileList=({1..10})
targetDir=$(cd ~/bolawen/scripts/test && pwd)
mkdir -p ${targetDir}
for file in ${fileList[@]}
do
dir=${targetDir}/${file}.txt
cat <<EOF > ${dir}
This is file ${file} head
This is file ${file} content
This is file ${file} tail
EOF
done