[内容] Linux while 循环

案例一:无限循环

#!/bin/bash

while ((1));
do
        sleep 1
        echo "infinite loop"
done

或者:

#!/bin/bash

while :
do
        sleep 1
        echo "infinite loop"
done

案例二:从 1 计数到 5

#!/bin/bash

i=1;n=5
while ((i <= n))
do

        echo $i
        let i++

done

或者:

#!/bin/bash

i=1;n=5
while [[ $i -le $n ]]
do

        echo $i
        let i++

done

案例三:从 1 加到 5

#!/bin/bash

i=1
while ((i <= 5));
do

        let sum=$sum+$i
        let i++

done

echo $sum

或者:

#!/bin/bash

i=1
while [[ $i -le 5 ]];
do

        let sum=$sum+$i
        let i++

done

echo $sum

案例四:输入多个数字,通过同时按下 “Ctrl” 键和 “D” 键结束输入,并将多个数字相加

#!/bin/bash

sum=0
echo "Please input number, press "ctrl" and "d" at the same time to end the input"

while read num
do
        let sum=$sum+$num
done

echo $sum

案例五:阅读文件

#!/bin/bash

while read line
do
        echo $line

done < test.txt

或者:

#!/bin/bash

cat test.txt | {
while read line
do
        echo $line

done }

或者:

#!/bin/bash

cat test.txt | while read line
do
        echo $line

done

(补充:这里以阅读 test.txt 文件为例)