Redirection Operators

in linux •  7 years ago 

Have you ever run a script and it goes too fast to see the output or there’s too much output and you can’t scroll back far enough. Then you need redirection.

The one I use the most would be to direct standard output to a text file for reference later.

SymbolFunction
>A new file will be created that will contain standard output. If you specify the same file name, the existing one will be overwritten.
>>Appends to an existing file. If the file does not exist it will be created.
2>Creates a new file that contains standard error. If the file already exists it will be overwritten.
2>>Appends standard error to an existing file and creates the file if it does not exist.
&>This will create a file that will contain standard output and standard error. If the file already exists it will be overwritten
<The contents of a file will be used as standard input.
<<Accepts text on the following lines as input
<>Causes the specified file to be used as standard input and standard output

One of the most common uses for redirection is to send output to /dev/null, /dev/null is a device that is connected to nothing so it’s like a black hole for unwanted data. Most of the time it would be used to discard error messages.

The << redirection is not typically used on the command line but more in scripts. You wouldn’t use it to specify a file like most of the others mentioned previously, as an example << EOF. Everything before the EOF would be passed as input to a command.

There’s one more I’d like to mention before i get to the most useful, which is pretty useful. tee, is used to send standard output to the terminal and to a specified file so that you can refer to it later.

[root@localhost ~]# ifconfig | tee ifconfig.txt
I know that I haven’t mentioned the most obvious one yet | (pipe), which you can see in use above. Normally ifconfig would show us the network interfaces and their properties. By adding the pipe it sends the output to tee which will then write the output to the file I’ve specified which is ifconfig.txt and it will output the information to the terminal. If I had used the following then it would create a new file or overwrite the file if it exists and not show any output on the terminal.

[root@localhost ~]# ifconfig > ifconfig.txt

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Congratulations @lokinc! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

You published your First Post

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!