
How to redirect input and output in Linux
sometimes you want to use output of a command as input for another command or you want to give content of a file as input of a command. in these situations, you need to know how to redirect input and output. today we will show you how to use these redirectors.
1- redirector categories
there is seven category of most important redirectos as shown below:
>
Creates a new file containing standard output. If the specified file exists, it’s overwritten. No file descriptor necessary.
>>
Appends standard output to the existing file. If the specified file doesn’t exist, it’s created. No file descriptor necessary.
2>
Creates a new file containing standard error. If the specified file exists, it’s overwritten. File descriptor necessary.
2>>
Appends standard error to the existing file. If the specified file doesn’t exist, it’s created. File descriptor necessary.
&>
Creates a new file containing both standard output and standard error. If the specified file exists, it’s overwritten. No file descriptors necessary.
<
Sends the contents of the specified file to be used as standard input. No file descriptor necessary.
<<
Accepts text on the following lines as standard input. No file descriptor necessary.
2- Examples
now we want to teach you how to use these redictors by examples.
example of >:
# ls -la > out.txt
in this example, we redirect output of “ls -la” commnad to a file named “out.txt”. so instead of showing output in terminal, it will save in “out.txt” file.
example of >>:
# ls -la >> out.txt
the difference between this and previous example is that, here the output of “ls -la” command will be appended to “out.txt” file, but in previous example, existing content of “out.txt” file will be cleared completely.
example of 2>:
imagine you have a program named “whine” that after running, will produce a lot error on terminal and you want to save it for further investigation. so in this case, we need to issue the following command:
# whine 2> err.txt
example of 2>>:
comparing to previous example, the difference is that, output error of “whine” program will be appended to “err.txt” file:
# whine 2>> err.txt
example of &>:
consider “whine” program. now we want to save any output of this program into a file. no matter if i’s standard or error:
# whine &> err.txt
example of <:
sometimes you create a backup of your mysql database and want to restore it again. simple and easy way is to use input redirector as show below:
# mysql -u root -p test < backup.sql
when we run this command, it will prompt for password and then content of “backup.sql” file will be inserted in “test” database.
example of <<:
instead of file content, we want to use keyboard to give input. this is very usefull for sending email with mail commnad:
mail -s "test" root@localhost << EOT
this command tells us to accept input form keyboard until “EOT” has been typed.