Say a file called abc
exists in the current directory and it has some text in it. When you execute the command:
cat abc > abc
Why do the contents of the the file abc
disappear?
Why does the command delete the text in it and the file becomes an empty file?
Best Answer
Because of the order how things are done.
When you do:
>
is the output redirection operator, when the shell sees this it opens the file in truncation mode usingO_TRUNC
flag withopen(2)
i.e.open("abc", O_TRUNC)
, so whatever was there in the file will be gone. Note that, this redirection is done first by the shell before thecat
command runs.So when the command
cat abc
executes, the fileabc
is already truncated hencecat
will find the file empty.