There are two ways of reading a file line by line that I want to discuss here:
#!/bin/bash
while read line
do
echo-e "$ line \ n"
done <file.txt
and
#!/bin/bash
exec 3<file.txt
while read line
do
echo-e "$ line \ n"
done
So first version works fine but I don't understand the mechanism of working while loop with the file. But the mechanism of the second version I understand. But here I don't understand why it hangs and does not print anything.
The first loop works because the redirection after the done
applies to the whole loop, so the read
there is reading from the file, not from the standard input of the script.
The second version hangs because read
reads from file descriptor 0, which is standard input, and you've not typed anything there. The exec
line redirects file descriptor 3 for reading from the file, but you're not reading from file descriptor 3.
You could rescue the second by using:
exec <file.txt
Now standard input is read from the named file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With