while [ CONDITION_IS_TRUE ]
do
command 1
command N
done
例如执行五次创建文件夹:
INDEX=1
while [ $INDEX -lt 6 ]
do
echo "Creating project-${INDEX}"
mkdir /usr/local/project-${INDEX}
((INDEX++))
done
while true
do
command N
sleep 1
done
可以用于for循环:
cd /var/www
for FILE in *.html
do
echo "Coping $FILE"
cp $FILE /var/www-just-html
done
例如读取某个文件pipeline到while循环里:
#!/usr/bin/env bash
LINE_NUMBER=1
cat /etc/passwd | while read LINE
do
echo "${LINE_NUMBER}: ${LINE}"
((LINE_NUMBER++))
done
结果将每行内容都打印出来并在开头加上了行号。