Files – How to Use Cat for IO Redirection

catfilesio-redirection

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:

cat abc > abc

> is the output redirection operator, when the shell sees this it opens the file in truncation mode using O_TRUNC flag with open(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 the cat command runs.

So when the command cat abc executes, the file abc is already truncated hence cat will find the file empty.

Related Question