The work of any command is either taking input or gives an output or both. So, Linux has some command or special character to redirect these input and output functionalities. For example: suppose we want to run a command called “date” if we run it will print the output to the current terminal screen. But our requirement is different, we don’t want the output to be displayed on the terminal. We want the output to be saved in a file. This could be done very easily with output redirection. Redirection here simply means diverting the output or input.
Similarly, if we have a command that needs input to be performed. Let take a command “head” this needs input to give output. So either we write input in the form of command directly or redirect input from any other place or file. Suppose we have a file called “file.txt” to print the starting some lines of the file we could use the “head”. So let’s see how this all is done on the terminal.
Types of Redirection
- “>” standard output
- “<" standard input
- “>>” standard output
- “<<" standard input
Implementation: So whatever you will write after running this command, all will be redirected and copied to the “file.txt”. This is standard output redirection.
cat > file.txt
Now, this is standard input redirection, cat command will take the input from “file.txt” and print it to the terminal screen. This line of code also shows the real working and meaning of cat command that is copy and paste. Many people have a misconception that the cat is used to create a file, but it is not true, the main work of the cat is to copy the input and give the output to the screen.
cat < file.txt
Let's see an example to understand the real work of cat command
Just type cat on the terminal and hit enter. It will ask for the input lines, you could write your name and hit enter. You will see your input will be reprinted.
(base) [root@localhost ~]# cat Hello this is GeeksForGeeks Hello this is GeeksForGeeks
This is used when we want to append some lines to the existing content of the file. If you use only a single angular bracket all the content of the file will be lost.
cat >> file.txt
To see the working of append standard input:
(base) [root@localhost ~]# cat << helo.txt > Hello This is > GeeksForGeeks Hello This is GeeksForGeeks (base) [root@localhost ~]#
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.