Shell使用技巧之逐行读取

重定向读取

#!/bin/bash
while read line
 do
   echo $line
 done < /etc/passwd 

管道读取

#!/bin/bash
cat /etc/passwd | while read line
do
  echo $line
done

文件描述符

#!/bin/bash
exec 3<"/etc/passwd"
while read line <&3
 do
  echo $line
 done

for循环

#!/bin/bash
IFS=$'
'
for file in `cat /etc/passwd`
 do
  echo $file
 done

# PS:这里的IFS格式设置不要错了,必须这么写IFS才能生效,其他方式都不对;

从执行速度上for最快、其次重定向、接着是文件描述符、最后是管道

参考文档:https://blog.csdn.net/apache0554/article/details/47006609

原文地址:https://www.cnblogs.com/guge-94/p/11119807.html