Reputation: 1674
I'm learning 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'm wondering is: Is either of them more common practice than the other? Are there performance differences? etc.
Also, are there other ways of reading from a file that are even better, especially when it comes to reading from large files?
Upvotes: 5
Views: 276
Reputation: 43019
There are a few advantages in the first method:
cat
and pipeEven if the while loop were to consume the output of another command (through process substitution as shown below), the first method is better as it eliminates the subshell:
while read -r line; do
# loop steps
done < <(_command_)
See also:
Upvotes: 3
Reputation: 249303
The second one is a Useless Use of Cat: http://porkmail.org/era/unix/award.html
I use the done < "$file"
form.
No, there is not a better way in Bash. But eliminating one process (cat
) is nice.
Upvotes: 5