Difference between while read line and for loop

while read line is to read the file information and assign it to the variable line at one time, while using the redirection mechanism, all the information in the file is read in and redirected to the line variable in the entire while statement.

 

for is to read a string delimited by spaces in the file at a time.

 

The following sample script:

 

    #/bin/bash
    IPS="10.1.1.10 3001
    10.1.1.10 3003
    10.1.1.11 3001
    10.1.1.11 3002
    10.1.1.11 3004
    10.1.1.11 3005
    10.1.1.13 3002
    10.1.1.13 3003
    10.1.1.13 3004
    10.1.1.14 3002"
    echo "====while test ===="
    i=0

    echo $IPS | while read line
    do
        echo $(($i+1))
        echo $line
    done


    echo "====for test ===="
    n=0
    for ip in $IPS ;
    do
       n=$(($n+1))
       echo $ip
       echo $n
    done

 

The output is as follows:

 

    ====while test ====
    1
    10.1.1.10 3001 10.1.1.10 3003 10.1.1.11 3001 10.1.1.11 3002 10.1.1.11 3004 10.1.1.11 3005 10.1.1.13 3002 10.1.1.13 3003 10.1.1.13 3004 10.1.1.14 3002
    ====for test ====
    10.1.1.10
    1
    3001
    2
    10.1.1.10
    3
    3003
    4
    10.1.1.11
    5
    3001
    6
    10.1.1.11
    ....

 

When there are multiple lines of text in the file, call the read statement again in the while loop to read the next record. The last line in $line has been read, and the next line of records cannot be obtained, thus exiting the while loop.

If you use a while loop and want to read one line at a time to the variable $line, you can use the following method:

#!/system/bin/sh
busybox cat /data/data/1.txt | while read LINE
do
adb shell gsr -m -p /data/data/$LINE 10000
done

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325298165&siteId=291194637