[shell] while read line 与for循环的区别

[shell] while read line 与for循环的区别

while read line 与for循环的区别 ---转载整理

while read line 是一次性将文件信息读入并赋值给变量line ,while中使用重定向机制,文件中的所有信息都被读入并重定向给了整个while 语句中的line 变量。

for是每次读取文件中一个以空格为分割符的字符串。

如下示例脚本:

  1. #/bin/bash
  2. IPS="10.1.1.10 3001
  3. 10.1.1.10 3003
  4. 10.1.1.11 3001
  5. 10.1.1.11 3002
  6. 10.1.1.11 3004
  7. 10.1.1.11 3005
  8. 10.1.1.13 3002
  9. 10.1.1.13 3003
  10. 10.1.1.13 3004
  11. 10.1.1.14 3002"
  12. echo "====while test ===="
  13. i=0
  14. echo $IPS while read line
  15. do
  16.     echo $(($i+1))
  17.     echo $line
  18. done
  19. echo "====for test ===="
  20. n=0
  21. for ip in $IPS ;
  22. do
  23.    n=$(($n+1))
  24.    echo $ip
  25.    echo $n
  26. done

输出结果如下:

 

  1. ====while test ====
  2. 1
  3. 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
  4. ====for test ====
  5. 10.1.1.10
  6. 1
  7. 3001
  8. 2
  9. 10.1.1.10
  10. 3
  11. 3003
  12. 4
  13. 10.1.1.11
  14. 5
  15. 3001
  16. 6
  17. 10.1.1.11
  18. ....

当文件中有多行文字,在while循环中再一次调用read语句,就会读取到下一条记录。而$line中的最后一行已经读完,无法获取下一行记录,从而退出 while循环。

若使用while循环,想每次读取其中1行内容到变量$line,则可以使用以下方法:

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

--------------------------------------------------------------------------------------------------------------------

原作者的【解决方法】---存疑,不太理解,后续学习
1 使用ssh -n "command" 
2 ssh "cmd" < /dev/null 将ssh 的输入重定向输入。

原文地址:https://www.cnblogs.com/davidshen/p/10275193.html