nerdexam
Linux_Foundation

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.

Submitted by yuriko_h· Apr 18, 2026Essential Commands

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

(32 responses)
  • A
    6% (2)
  • C
    91% (29)
  • D
    3% (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.

AThe file order is incorrect. The destination file must be mentioned before the command to ensure

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.

BThe command sed did not match anything in that file therefore the output is empty.

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.

CWhen the shell establishes the redirection it overwrites the target file before the redirectedCorrect

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.

DRedirection for shell commands do not work using the > character. It only works using the |

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

#Shell Redirection#Command Execution Order#File Truncation#sed command

Community Discussion

No community discussion yet for this question.

Full LFCS Practice