When the output of a command is redirected to a file, the output file is created or truncated by the shell before the command is executed, any idea what cat foo > foo does?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
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.
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.