Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash while loop that reads file line by line

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.

like image 287
Narek Avatar asked Dec 20 '11 06:12

Narek


1 Answers

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.

like image 102
Jonathan Leffler Avatar answered Oct 23 '22 00:10

Jonathan Leffler