What is a good use of the output redirection operator ">"?

Question

The example given for the use of output redirection here:

cat oceans.txt > continents.txt

focuses on overwriting the contents of an existing file. What is another common use for this operation?

Answer

First, let’s note that > can also be used to create files. In the example above for instance, if we replace continents.txt by newFile.txt, where newFile.txt doesn’t already exist in the directory,

cat oceans.txt > newFile.txt

will create the newFile.txt, store it in the current directory, and make its contents the exact same as oceans.txt. With that in mind, another common use for > is to store the output of a program in a new file. It is likely that you have run a program at some time or other and watched as a lot of text speeds by on your screen. This is fine sometimes but in other cases you may want to store that text for further analysis. One way to do this on the command line is to run the program on the left side of > and add the name that you would like to call the new file (or an old file to be overwritten) on the right side. For instance, if the program executable is called a.out and I want the output to be stored in a file called out.txt, I write

./a.out > out.txt
19 Likes

cp a.txt b.txt seems to work the same as cat a.txt > b.txt, because both commands overwrite the content of b.txt with that of a.txt.

Is there any difference in usage/behavior between the two?

9 Likes

cp is kind of a COPY PASTE think about it that way - it copies file/directories. But it’s not transferring files (it’s not a cut paste) just copy paste. CAT is kind of a CUT PASTE. You are transferring file/directories from one file to the other. It also allows you create a new file in the process.

6 Likes

da bo dase wake kana che bas copy past bo wake nur te ta beghama sha :slightly_smiling_face: