4 ms·
Yes, that's a good way to think of it. Because under the hood redirects use the dup2() syscall (with some elaboration). What is dup2()? It's basically an ass
by chubot 5y ago
Yes, that's a good way to think of it. Because under the hood redirects use the dup2() syscall (with some elaboration).
What is dup2()? It's basically an assignment of the things that file descriptors point to. Why not use regular assignment? Because the things they point to live in the kernel's memory, not your own address space :)
Here I describe file descriptors as "pointers" from user space into the kernel. They are integers and not literal pointers because they're in a different address space.
Three Comics For Understanding Unix Shell: https://www.oilshell.org/blog/2020/04/comics.html https://www.oilshell.org/blog/2020/04/comics.html
So yes redirects are a very low level and somewhat confusing syntax, and you have to understand how the kernel works to really understand them.
----
Although I didn't really understand this until I implemented a shell, and instead I mostly used these canned patterns:
sort < myfile
mycmd 2>&1
mycmd 2>&1 | wc -l # stdout and stderr to pipe
mycmd >file.txt 2>&1 # stdout and stderr to file
echo error >&2
That's about all you need. Related:
Avoid Directly Manipulating File Descriptors in Shell: https://www.oilshell.org/blog/2017/08/12.html https://www.oilshell.org/blog/2017/08/12.html (all usages of say 4>&5 can be done simply by regular direction of shell FUNCTIONS, no need to juggle them manually)