Sample Header Ad - 728x90

How (internally) does fd3>&fd1 after { fd1>&fd3 } put back (or not) original fd into fd1? ("bad file descriptor")

5 votes
2 answers
400 views
`I'm reading an answer to https://stackoverflow.com/questions/692000/how-do-i-write-standard-error-to-a-file-while-using-tee-with-a-pipe/692009#692009 , https://stackoverflow.com/a/14737103/5499118 : { { ./aaa.sh | tee bbb.out; } 2>&1 1>&3 | tee ccc.out; } 3>&1 1>&2 As I've checked it works as explained, the answer links to https://unix.stackexchange.com/a/18904/266260 which links to https://unix.stackexchange.com/a/3540/266260 . I don't understand why { ... 1>&3 ... } 3>&1 works (how the later redirection reverses effect of the former), because when I wanted to understand man bash: > Note that the order of redirections is significant. For example, the > command > > ls > dirlist 2>&1 > > directs both standard output and standard error to the file dirlist, > while the command > > ls 2>&1 > dirlist > > directs only the standard output to file dirlist, because the standard > error was duplicated from the standard output before the standard > output was redirected to dirlist. I've found https://unix.stackexchange.com/questions/248012/duplication-of-file-descriptors-in-redirection : > Redirections are implemented via the dup family of system functions. > dup is short for duplication and when you do e.g.: > > 3>&2 > > you duplicate (dup2 ) filedescritor 2 onto filedescriptor 3 ... Therefore I understand 1>&3 duplicates 3 into 1 and they point to the same object from that command on. man dup: > After a successful return, the old and new file descriptors may be > used interchangeably. They refer to the same open file description From dup explanation I expect 3>&1 to change nothing as 3 and 1 are already the same. But apparently it is not the case as omitting 3>&1 from { { ./aaa.sh | tee bbb.out; } 2>&1 1>&3 | tee ccc.out; } 3>&1 1>&2 results in bash: 3: bad file descriptor What (if any) is incorrect in explaining redirection with dup calls? What internally happens during 1>&3 and 3>&1? Maybe { } are important here, but I see they are used for grouping only and per man bash: > list is simply executed in the current shell environment.
Asked by Alex Martian (1287 rep)
Apr 19, 2025, 04:33 AM
Last activity: Apr 20, 2025, 01:34 PM