In UNIX what "cat file1 > file1 does?" In UNIX what "cat file1 > file1 does?" unix unix

In UNIX what "cat file1 > file1 does?"


In all cases, the file is truncated. That’s because redirection is handled by the shell, which opens the file for writing before invoking the command.

cat foo > foo

The shell truncates and opens foo for writing, sets stdout to the file, and then exec’s ["cat", "foo"].

GNU cat is smart and refuses to redirect a file to itself. It does this by checking the device/inode pair on the input and output file descriptors; you can read the wonderful low-level details in src/cat.c. It prints a message and quits.

BSD cat doesn’t have such a safety, but since the file has already been truncated, there is nothing to read, nothing to write, and it will halt.


You can spice things up a bit by appending instead of truncating.

echo hello > foocat foo >> foo

Now everything is the same except the shell opens the file for appending instead of truncating it.

GNU cat sees what you’re doing and stops; the file is untouched.

BSD cat goes into a loop and appends the file to itself until your disk fills up.


On Fedora 13 this is what I see

cat foo > foocat: foo: input file is output file

If foo contained anything previously, it is gone.


The file is truncated first and then read, so this command would truncate the file.

When I tried to execute it I got this warning:

cat: test.txt: input file is output file