In this article, we cover how to redirect output of a command in Linux. Certain conditions require standard output of a Linux command to be written to a file. Or, we can also use the standard output of a command as standard input for another Linux command. This can easily be achieved through > (greater than) and | (pipe) operators.
> greater than operator is used to write output to a file while | pipe operator redirects the output of one command as input to another command.
We will be covering three redirect conditions here –
- write standard output to a file,
- append standard output to a file and,
- standard output as input to another command.
Redirect output of a command in Linux
I. Write standard output to a file –
As already covered, we will be using > (or, greater than) operator to redirect standard output to a file. There is a word of caution here, if the file with same name already exists then content of the file would be replaced with standard output. Therefore, check beforehand for an existing file and just make sure that you don’t inadvertently overwrite an existing file. Though there are numerous ways to redirect command output. Just to give you an idea on how things work, issue the following in terminal –
cat /etc/hosts > /dev/shm/copy-hosts
This would write contents of hosts file to the file copy-hosts. Or, we can write the output of ls command to a file –
ls -al > /dev/shm/ls-copy
II. Append standard output to a file –
In section I, we saw how a single greater than operator would overwrite an existing file. But, what if we want to write the standard output at the end of an existing file? In that case, we have to use two greater than operators (>>).
We continue with above examples but this time with different command set –
date >> /dev/shm/copy-hosts
or,
cat /etc/hosts >> /dev/shm/ls-copy
Now, open both the files to check if it works the way it should. Both the files would contain output from section I.
III. Lastly, redirecting standard output of a command to input of another Linux command –
This we can achieve through | pipe operator. For instance,
cat /etc/hosts | grep localhost
This would print the lines wherever localhost is present in the /etc/hosts file.
In conclusion, we have covered how to redirect standard output of a Linux command.