nerdexam
LPI

010-160 · Question #57

Why is the file data.txt empty after executing sort data.txt > data.txt?

The correct answer is D. Because the file gets truncated before sort is executed. The shell truncates the redirection target file before the command starts executing, so sort reads an already-empty file and writes nothing.

The Power of the Command Line

Question

Why is the file data.txt empty after executing sort data.txt > data.txt?

Options

  • ABecause, if data.txt is empty now, it must have been empty before.
  • BBecause sort cannot sort text files, only binary files.
  • CBecause sort detects that both files are the same.
  • DBecause the file gets truncated before sort is executed.
  • EBecause the file is locked and cannot be written to.

How the community answered

(54 responses)
  • A
    15% (8)
  • B
    2% (1)
  • C
    9% (5)
  • D
    70% (38)
  • E
    4% (2)

Why each option

The shell truncates the redirection target file before the command starts executing, so sort reads an already-empty file and writes nothing.

ABecause, if data.txt is empty now, it must have been empty before.

The file was not originally empty; the shell's redirection mechanism is what caused the truncation, making it appear as though it was always empty.

BBecause sort cannot sort text files, only binary files.

sort is a text-processing utility designed specifically to sort lines of text; it has no restriction against text files.

CBecause sort detects that both files are the same.

sort does not perform any same-file detection; the shell handles redirection independently of and prior to invoking sort.

DBecause the file gets truncated before sort is executed.Correct

When the shell processes a command containing >, it opens and truncates the destination file to zero bytes before launching the command. This means data.txt is emptied before sort even opens it for reading, so sort receives no input and the file remains empty after the command exits.

EBecause the file is locked and cannot be written to.

No file locking prevents the write; the shell successfully opens and truncates the file, which is precisely why it ends up empty.

Concept tested: Shell I/O redirection truncation before command execution

Source: https://www.gnu.org/software/bash/manual/bash.html#Redirecting-Output

Topics

#shell redirection#output redirection#file truncation#sort command

Community Discussion

No community discussion yet for this question.

Full 010-160 Practice