0

In my observation, echo to regular file echo >>regular_file opens the file, appends to it, and then closes the file. Whereas echo to an open file descriptor echo >>&fd* doesn't close it. Is this behavior documented somewhere in bash/zsh manuals?

* here fd can be a number like 3.

1
  • There is no echo to an open file descriptor. The command echo Hello >>&3 will write to file 3 (in zsh only. In bash there is a similar &>>). There is no fd to close, but the file yes, gets closed. Commented Aug 29, 2022 at 5:31

1 Answer 1

2

The syntax echo >>&fd is not defined by POSIX, Bash or zsh, I assume you meant echo >&fd. Both operations involve file descriptor duplication, but the first one involves first opening the specified file. In echo >>regular_file (which is equivalent to echo 1>>regular_file, where fd 1 is standard output) the shell first opens regular_file, this operation returns a file descriptor, then the returned fd is duplicated to standard output fd 1, and the former is closed. After the command finishes execution, fd 1 is "restored" (not necessarily done if a fork is made, but whatever way it's done, fd 1 refers to the same file it referred to before executing the command).

The second command echo >&fd (again, equivalent to echo 1>&fd) only duplicates fd to stdout and does not close fd. Again, standard output is restored after execution of the command.

It's clearer to refer to the first operation as redirection and the second one as file descriptor duplication, as documented by POSIX shell command language, and other shells.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .