010-150 · Question #59
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. Shell redirection with > truncates (empties) the output file before the command begins executing, so sort reads from an already-empty file. This is a well-known shell behavior when input and output refer to the same file.
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.
How the community answered
(58 responses)- A3% (2)
- B12% (7)
- C3% (2)
- D81% (47)
Why each option
Shell redirection with > truncates (empties) the output file before the command begins executing, so sort reads from an already-empty file. This is a well-known shell behavior when input and output refer to the same file.
The file was not empty before the command; the truncation caused by the redirection operator is what emptied it.
sort is designed to sort text files; it works correctly on plain text and the file type is not the issue here.
sort does not detect or handle the case where input and output are the same file; the shell's redirection mechanism, not sort itself, is responsible for the truncation.
When the shell processes sort data.txt > data.txt, it sets up the redirection first by opening data.txt for writing and truncating it to zero bytes before sort even starts. By the time sort opens data.txt for reading, the file is already empty, so there is nothing to sort and the output written back is also empty.
Concept tested: Shell output redirection truncation order of operations
Source: https://www.gnu.org/software/bash/manual/bash.html#Redirections
Topics
Community Discussion
No community discussion yet for this question.