3

I have a file which contains four lines:

$ cat file
First line
Second line
Third line
Fourth line
$ 

When I read this file four times, then I always read the first line which is an expected result:

$ for i in {1..4}; do read line <file; echo "$line" ; done
First line
First line
First line
First line
$ 

However, when I link file descriptor 3 with file and then read it in the same fashion, then each read "eats" the input stream:

$ exec 3<file
$ for i in {1..4}; do read -u 3 line; echo "$line" ; done
First line
Second line
Third line
Fourth line
$

Why do file descriptors behave like this?

  • Is the behaviour not similar in all POSIX compliant shells? If so we can also tag it with /shell. – Bob May 29 '17 at 20:14
  • @Bob I changed "bash" tag to "shell" tag. – Martin May 29 '17 at 20:38
4

When you say: read var <file the file-descriptor is closed once the command finishes. Hence, the next time around in the loop, the file-descriptor is reset to the beginning.

In the case of exec 3<file, when you say read -r -u 3 var the file descriptor stays open even when the read command finishes AND the read position is updated so the next time around, the read will grab the next line.

Note: Even if you had done, exec 0<file and then read -r var it will still behave similarly.

3

The quick answer is that is how they are designed to work - a file descriptor contains a state, which includes a read and write position. Every read performed on one file descriptor moves the read position, no matter who is reading from it - the file descriptor only contains one read position.

In another way, when a file descriptor is created (by the OS), it also creates a struct/table that contains these state variables. There is only one copy of the read position in the table, and every time the read() function is called on the file descriptor, the single read position variable is updated.

  • Unix systems (AFAIK) contain a single file position, used for both reading and writing. Also, each process gets its own file descriptor table, so they can be operating on different parts of the file at the same time. – gardenhead May 30 '17 at 2:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.