[内容] 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

案例四:输入多个数字,每输入 1 个数字后就需要按下回车,通过同时按下 “Ctrl” 键和 “D” 键结束输入,并将多个数字相加

#!/bin/bash

sum=0
echo 'Please input number, you must press 'enter' after inputting each 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 文件为例)

案例六:阅读文件 (1 列接着 1 列阅读,并可以把每 1 列的内容分开)

6.1 创建要被阅读的文件

# vi test.txt

创建以下内容:

no1 user1 test1.txt
no2 user2 test2.txt
no3 user3 test3.txt
no4 user4 test4.txt
no5 uesr5 test5.txt

6.2 阅读文件 (1 列接着 1 列阅读,并可以把每 1 列的内容分开)

# cat test.txt | while read no user file ;do echo $no $file;done
no1 test1.txt
no2 test2.txt
no3 test3.txt
no4 test4.txt
no5 test5.txt