5

I have been looking and couldnt find clear clues to verify what I am deducing from a script given to me.

so file.txt is an opened file (by the file descriptor 3) and is constantly adding a new line by a script that records timestamp. Does the following piece make into the while loop each time a new line is added to the file?

exec 3 < /path/file.txt
while read <&3
  command
  command..
done

So as long as I dont close the file descriptor, a new line added to my file.txt will always activate the while loop, right?

Please help me clear this up. Thanks

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
savingday
  • 51
  • 1
  • 7
  • you might be interested in a detailed explanation of `exec` http://stackoverflow.com/questions/18351198/what-are-the-uses-of-the-exec-command-in-shell-scripts – xiaowl Dec 08 '14 at 07:10

2 Answers2

8

To read from file descriptor 3, use read -u 3 (see Bash builtins). Don't forget to specify the variable name into which the value should be read.

Once read detects EOF, it stays at EOF; it won't spot additions to the file after that. So, if the code adding lines to the file is slower than the code in this script, you will reach and end point and the loop will terminate. If you don't want that, consider using tail -f /path/file.txt, and maybe process substitution too:

while read -u 3 line
do
    command1
    command2
done 3< <(tail -f /path/file.txt)

Or, if you want to do the exec:

exec 3< <(tail -f /path/file.txt)

while read -u 3 line
do
    command1
    command2
done

Note that the tail -f loops will never finish until you interrupt the script in some way.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • `read -u 3` allows redirection from a file descriptor on a `per code-block basis` without requiring a manual open of the descriptor with `exec`. `while read <&3` is fine where the descriptor is opened with `exec` and will require a close with `exec 3>&-`. – David C. Rankin Dec 08 '14 at 07:04
3

So as long as I dont close the file descriptor, a new line added to my file.txt will always activate the while loop, right?

Answer: wrong.

Redirecting exec 3 < /path/file.txt gives you the ability to read from /path/file.txt using the file descriptor, but does nothing to allow any type of triggering from /path/file.txt to your code. Think about it this way. If there is a new line in /path/file.txt, you can read it, but the redirection provides no way of knowing whether or not a new line has been added to the file for your code to respond to. It's still up to your code to check.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85