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?
The cat (short for “concatenate“) command is one of the most frequently used commands in Linux/Unix-like operating systems. cat command allows us to create single or multiple files, view content of a file, concatenate files and redirect output in terminal or files.
If you have worked in Linux, you surely have seen a code snippet that uses the cat command. Cat is short for concatenate. This command displays the contents of one or more files without having to open the file for editing.
7) Cat command can append the contents of one file to the end of another file. Command: $cat file1 >> file2. Output. Will append the contents of one file to the end of another file.
mv (move) mv file1 file2 moves (or renames) file1 to file2. This has the effect of moving rather than copying the file, so you end up with only one file rather than two. It can also be used to rename a file, by moving the file to the same directory, but giving it a different name.
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 > foo
cat 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With