LX0-103 · Question #49
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. Shell redirection truncates the output file before the command executes, so sed reads an already-empty file.
Question
When running the command sed -e "s/a/b/" /tmp/file >/tmp/file While /tmp/file contains data, why is /tmp/file empty afterwards?
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
(28 responses)- A7% (2)
- B7% (2)
- C68% (19)
- D18% (5)
Why each option
Shell redirection truncates the output file before the command executes, so sed reads an already-empty file.
The syntax is valid - sed takes the input file as an argument and the output redirection follows the command, which is correct shell syntax.
Whether the pattern matches is irrelevant here; the file is empty before sed even runs, due to shell redirection behavior, not a failed substitution.
When the shell parses the command line, it sets up all redirections before executing any command. The > operator causes the shell to open /tmp/file with O_TRUNC, which zeroes it out immediately. By the time sed tries to read /tmp/file as input, the file is already empty, producing no output and leaving the destination file empty.
The > character is a valid output redirection operator in bash; | is for piping between commands, which is a separate and unrelated mechanism.
Concept tested: Shell output redirection file truncation before command execution
Source: https://www.gnu.org/software/bash/manual/bash.html#Redirections
Topics
Community Discussion
No community discussion yet for this question.