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.
Question
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)- A15% (8)
- B2% (1)
- C9% (5)
- D70% (38)
- E4% (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.
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.
sort is a text-processing utility designed specifically to sort lines of text; it has no restriction against text files.
sort does not perform any same-file detection; the shell handles redirection independently of and prior to invoking sort.
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.
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
Community Discussion
No community discussion yet for this question.