Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In UNIX what "cat file1 > file1 does?"

Tags:

redirect

unix

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?

like image 946
HelloWorld Avatar asked Oct 08 '10 04:10

HelloWorld


People also ask

What does cat function do in Unix?

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.

What does cat mean in Unix?

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.

What does cat file1 file2 mean?

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.

Which command will transfer contents of file1 to file2?

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.


1 Answers

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.

like image 157
Josh Lee Avatar answered Nov 17 '22 16:11

Josh Lee