5 ms·
good one.. when I checked on Linux, both `cat` and `grep` give error when input file name is same as output... but not `sed/awk/head/tail/sort/etc`..
by asicsp 9y ago
good one..
when I checked on Linux, both `cat` and `grep` give error when input file name is same as output... but not `sed/awk/head/tail/sort/etc`..
- goialoq 9y agoIf you redirect output, how can the command know the name of the destination?
- aaronmdjones 9y agofstat(2) on the output file descriptor, stat(2) on the input file name, see if they have the same block device and inode numbers.
- xxs 9y agoRedirecting (in simple terms) is setting a file descriptor. So the file descriptor can be tested if it partakes in the input. A quote for you [0]: Under normal circumstances every UNIX program has three streams opened for it when it starts up, one for input, one for output, and one for printing diagnostic or error messages. These are typically attached to the user's terminal (see tty(4) but might instead refer to files or other devices, depending on what the parent process chose to set up. (See also the "Redirection" section of sh(1).) [0]: https://linux.die.net/man/3/stdout https://linux.die.net/man/3/stdout
- Karliss 9y agoSomewhat more common use of this is to check if output goes to terminal so that terminal color codes don't get printed to files.
- rocqua 9y agoWhich is really annoying when you want to pipe grep to less, and need to add --color=always to get grep to understand less takes color codes (when using less -R).
- raimue 9y agoIn most cases, it is too late anyway at that point, as the shell redirection already truncated the file. Such a check might only help you realize you just deleted the text you wanted to process.
- asicsp 9y agoyeah agree.. here I was specifically checking append, where it doesn't get truncated...