Search code examples
bashfile-iofile-descriptor

How do Bash local file descriptors work?


I have looked but can't find any Bash guide that describes the details for how the following file descriptor syntax works:

while read line <&3; do
    echo $line
done 3<file.txt

Is this a special construction for while loops that allows Bash to look after the done for the file descriptor source? Is it some kind of shorthand for making an exec call?


Solution

  • There's nothing special about it other than the fact that the whole redirection thing is a wholly brilliant concept.

    The <&3 simply tells read to take it's input from file handle 3 and the 3<file.txt simply sets up file handle 3 for the relevant command set, which is the entire while loop.

    You can read up on it in the bash man page under REDIRECTION.

    You could also use the file desriptor form of read -u 3 which I prefer since it allows me to get at both standard input and the extra file handle within the loop.

    And, if you're thinking that somehow, file handle 3 is used before being set up, that's not so. The 3<file.txt applies to the entire while..done loop, think of it like this:

    (
        while read line <&3; do
            echo $line
        done
    ) 3<file.txt
    

    In that sense, it's no different to:

    sed 's/^/xx:/' <file.txt
    

    in that the redirection is done for the command, not following it.