When running the command -
sed -e "s/a/b/" /tmp/file >/tmp/file
While /tmp/file contains data, why is /tmp/file empty afterwards?
Click on the arrows to vote for the correct answer
A. B. C. D.C
The command sed -e "s/a/b/" /tmp/file >/tmp/file
is intended to substitute the first occurrence of the character 'a' with 'b' in the file /tmp/file
and then redirect the output to the same file /tmp/file
. However, when the command is run, the file /tmp/file
becomes empty, and the reason for this behavior is not immediately apparent.
The correct answer to this question is C. When the shell establishes the redirection, it overwrites the target file before the redirected command starts and opens it for reading. This means that when the shell sees >/tmp/file
at the end of the command, it truncates the file /tmp/file
to zero length before running the sed
command. As a result, the sed
command does not find anything in the file to substitute, and therefore does not produce any output.
To understand this behavior, it is useful to know how shell redirection works. In Linux, when a shell command is executed, the shell interprets the command line and identifies any input or output redirection requests. Redirection is indicated by the >
symbol in this case. The shell then performs the following steps:
The shell opens the destination file (/tmp/file
in this case) for writing, truncating it to zero length if it already exists.
The shell sets up a pipe between the command's standard output and the destination file.
The shell launches the command (sed -e "s/a/b/" /tmp/file
in this case).
The command runs and writes its output to the pipe.
The shell reads data from the pipe and writes it to the destination file.
In this case, the shell truncates the file /tmp/file
to zero length before the sed
command runs. As a result, the sed
command does not find any occurrences of the character 'a' in the file and does not produce any output. When the shell tries to read data from the pipe and write it to the destination file, there is no data to write, so the file remains empty.
In summary, the correct answer is C: the shell establishes the redirection by overwriting the target file before the redirected command starts and opens it for reading. This behavior can lead to unexpected results if the user is not aware of it.