LFCS · Question #862
When running the command sed -e "s/a/b/" /tmp/file >/tmp/file While /tmp/file contains data, why is /tmp/file empty afterwards?
The correct answer is C. When the shell establishes the redirection it overwrites the target file before the redirected. When the shell redirects output to the same file that a command reads as input, the shell truncates the file before the command can read it, leading to an empty file.
Question
Options
- AThe file order is incorrect. The destination file must be mentioned before the command to ensure
- BThe command sed did not match anything in that file therefore the output is empty.
- CWhen the shell establishes the redirection it overwrites the target file before the redirected
- DRedirection for shell commands do not work using the > character. It only works using the |
How the community answered
(32 responses)- A6% (2)
- C91% (29)
- D3% (1)
Why each option
When the shell redirects output to the same file that a command reads as input, the shell truncates the file before the command can read it, leading to an empty file.
The file order is generally `command input_file > output_file`, and the issue stems from the shell's handling of redirection, not an incorrect argument order for `sed` itself.
Even if `sed` did not match anything, it would typically pass the original input lines to stdout, but the core problem is that `sed` receives no input because the file is truncated first.
When the shell establishes output redirection using `>` to `/tmp/file`, it opens `/tmp/file` for writing and truncates its contents to zero size immediately. By the time `sed` attempts to read its input from `/tmp/file`, the file is already empty, resulting in `sed` processing no data and thus producing no output, leaving `/tmp/file` empty.
The `>` character is the correct and standard shell operator for redirecting standard output to a file, but its execution timing is critical in this scenario.
Concept tested: Shell redirection order of operations
Source: https://www.gnu.org/software/bash/manual/bash.html#Redirection
Topics
Community Discussion
No community discussion yet for this question.