nerdexam
CompTIA

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.

GNU and Unix 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

(28 responses)
  • A
    7% (2)
  • B
    7% (2)
  • C
    68% (19)
  • D
    18% (5)

Why each option

Shell redirection truncates the output file before the command executes, so sed reads an already-empty file.

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

The syntax is valid - sed takes the input file as an argument and the output redirection follows the command, which is correct shell syntax.

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

Whether the pattern matches is irrelevant here; the file is empty before sed even runs, due to shell redirection behavior, not a failed substitution.

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

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.

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

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

#shell redirection#sed#file truncation#execution order

Community Discussion

No community discussion yet for this question.

Full LX0-103 Practice