What is the best way to write a loop that is read from a file?

I am studying bash and trying to understand the difference between these two methods of reading lines from a file.

1.

while IFS= read -r line
do
  echo $line
done < "$file"

2.

cat $file |
while read data
do
   echo $i
done

So basically what I am interested in is: Is one of them more common practice than the other? Are there differences in performance? and etc.

Also, are there other ways to read from a file that are even better, especially when it comes to reading from large files?

+4
source share
2 answers

The second is the useless use of Cat: http://porkmail.org/era/unix/award.html

I am using a form done < "$file".

No, there is no better way in Bash. But eliminating one process ( cat) is nice.

+5

:

  • cat pipe
  • , ; , ,

while ( , ), , :

while read -r line; do
  # loop steps
done < <(_command_)

. :

+3

Source: https://habr.com/ru/post/1677096/


All Articles