Learn The Basics of How Linux I/O (Input/Output) Redirection Works


Aaron Kili


For instance to append the output of top command above in the top.log file especially within a script (or on the command line), enter the line below: $ top -bn 5 »top.log Note: Using the file descriptor number, the output redirect command above is the same as: $ top -bn 5 1>top.log How To Redirect Standard Error to File in Linux To redirect standard error of a command, you need to explicitly specify the file descriptor number, 2 for the shell to understand what you are trying to do. The first is a relatively old method which works as follows: $ ls -l /root/ >ls-error.log 2>&1 The command above means the shell will first send the output of the ls command to the file ls-error.log (using >ls-error.log ), and then writes all error messages to the file descriptor 2 (standard output) which has been redirected to the file ls-error.log (using 2>&1 ). The second and direct method is: $ ls -l /root/ &>ls-error.log You can as well append standard output and standard error to a single file like so: $ ls -l /root/ &»ls-error.log How To Redirect Standard Input to File Most if not all commands get their input from standard input, and by default standard input is attached to the keyboard. To redirect standard input from a file other than the keyboard, use the “<” operator as below: $ cat <domains.list How To Redirect Standard Input/Output to File You can perform standard input, standard output redirection at the same time using sort command as below: $ sort sort.output How to Use I/O Redirection Using Pipes To redirect the output of one command as input of another, you can use pipes, this is a powerful means of building useful command lines for complex operations. $ ls -lt | head -n 5 Here, the options: -l – enables long listing format -t – sort by modification time with the newest files are shown first -n – specifies the number of header lines to show Important Commands for Building Pipelines Here, we will briefly review two important commands for building command pipelines and they are: xargs which is used to build and execute command lines from standard input.


Visit Link


Tags: