0

This is a Linux-specific question.

The bash script is:

echo foo > "a.txt"
exec 3<"a.txt"
cat /dev/fd/3
cat /dev/fd/3
cat /dev/fd/3

Output:

foo
foo
foo

All these cats display the content of /dev/fd/3. But /dev/fd/3 is simply a symlink to a.txt. That explains the behavior but I don't know if it's guaranteed (and if so, by what) that:

  1. When you run exec 3<"a.txt", /dev/fd/3 is always a symlink to a.txt.

  2. Every time you open and read from /dev/fd/3, it returns the entire body.

There is an answer to a similar but not entirely same question:

https://unix.stackexchange.com/a/58124/7157

  • cat </dev/fd/3 is more portably written cat <&3. I can't reproduce what you are seeing. Only the first cat should output the whole of a.txt. In essence, what you have is { cat; cat; cat; } <"a.txt" – Kusalananda Dec 10 '19 at 9:51
  • /dev/fd/3 is most definitely not a symlink to anything. – AlexP Dec 10 '19 at 10:01
  • 1
    @Cyker that's what the kernel tells ls, to be more friendly. It's not a link. The filesystem itself is virtual, so it's not even a real file. – muru Dec 10 '19 at 10:30
  • 1
    @Cyker I don't have /proc (I'm not on Linux). The /dev/fd/3 is a character special file (just like /dev/tty), definitely not a symbolic link. – Kusalananda Dec 10 '19 at 11:02
  • 1
    @muru stop bamboozling the OP. every file/system is "virtual" on linux. FWIW, yes, on Linux opening /dev/fd/N -> /proc/self/fd/N -> /path/to/the/original/file will always open the original file it points to from scratch, and this is completely different from OpenBSD, Solaris, etc where open("/dev/fd/N", ...) will act just like dup(N), ie will duplicate the fd. – mosvy Dec 10 '19 at 11:09

Your Answer

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

Browse other questions tagged or ask your own question.