- Learn The Basics of How Linux I/O (Input/Output) Redirection Works
- How To Redirect Standard Output to File in Linux
- How To Redirect Standard Error to File in Linux
- How To Redirect Standard Output/ Error To One File
- How To Redirect Standard Input to File
- How To Redirect Standard Input/Output to File
- How to Use I/O Redirection Using Pipes
- Important Commands for Building Pipelines
- Ввод/вывод в Linux и их перенаправление
- Ввод, вывод и потоки
- Understanding Standard I/O on Linux
- Standard Input
- Standard Output
- Standard Error
- How to Redirect Input and Output on Linux
- Standard I/O Works Everywhere
Learn The Basics of How Linux I/O (Input/Output) Redirection Works
One of the most important and interesting topics under Linux administration is I/O redirection. This feature of the command line enables you to redirect the input and/or output of commands from and/or to files, or join multiple commands together using pipes to form what is known as a “command pipeline”.
All the commands that we run fundamentally produce two kinds of output:
- the command result – data the program is designed to produce, and
- the program status and error messages that informs a user of the program execution details.
In Linux and other Unix-like systems, there are three default files named below which are also identified by the shell using file descriptor numbers:
- stdin or 0 – it’s connected to the keyboard, most programs read input from this file.
- stdout or 1 – it’s attached to the screen, and all programs send their results to this file and
- stderr or 2 – programs send status/error messages to this file which is also attached to the screen.
Therefore, I/O redirection allows you to alter the input source of a command as well as where its output and error messages are sent to. And this is made possible by the “” redirection operators.
How To Redirect Standard Output to File in Linux
You can redirect standard output as in the example below, here, we want to store the output of the top command for later inspection:
- -b – enables top to run in batch mode, so that you can redirect its output to a file or another command.
- -n – specifies the number of iterations before the command terminates.
You can view the contents of top.log file using cat command as follows:
To append the output of a command, use the “>>” operator.
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:
Note: Using the file descriptor number, the output redirect command above is the same as:
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.
For example the ls command below will produce an error when executed by a normal system user without root privileges:
You can redirect the standard error to a file as below:
$ ls -l /root/ 2>ls-error.log $ cat ls-error.log
In order to append the standard error, use the command below:
How To Redirect Standard Output/ Error To One File
It is also possible to capture all the output of a command (both standard output and standard error) into a single file. This can be done in two possible ways by specifying the file descriptor numbers:
1. The first is a relatively old method which works as follows:
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 ). Implying that standard error is also sent to the same file as standard output.
2. The second and direct method is:
You can as well append standard output and standard error to a single file like so:
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 “
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:
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.
- -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. Below is an example of a pipeline which uses xargs, this command is used to copy a file into multiple directories in Linux:
$ echo /home/aaronkilik/test/ /home/aaronkilik/tmp | xargs -n 1 cp -v /home/aaronkilik/bin/sys_info.sh
- -n 1 – instructs xargs to use at most one argument per command line and send to the cp command
- cp – copies the file
- -v – displays progress of copy command.
For more usage options and info, read through the xargs man page:
A tee command reads from standard input and writes to standard output and files. We can demonstrate how tee works as follows:
$ echo "Testing how tee command works" | tee file1
File or text filters are commonly used with pipes for effective Linux file operations, to process information in powerful ways such as restructuring output of commands (this can be vital for generation of useful Linux reports), modifying text in files plus several other Linux system administration tasks.
To learn more about Linux filters and pipes, read this article Find Top 10 IP Addresses Accessing Apache Server, shows a useful example of using filters and pipes.
In this article, we explained the fundamentals of I/O redirection in Linux. Remember to share your thoughts via the feedback section below.
Ввод/вывод в Linux и их перенаправление
Давненько у нас не было материалов для новичков в системном администрировании и желающих получше узнать подноготную Linux-дистрибутивов. Исправляюсь и далее расскажу про перенаправление ввода/вывода в Linux, стараясь сделать это просто и понятно.
Если вы подписаны на канал, но еще не приняли участие в конкурсе, то нужно это исправлять как можно быстрее! Если вы еще не подписаны на Просто Код, то быстренько подписываетесь и переходите по ссылке ниже, чтобы узнать подробности розыгрыша и описание призов.
Конкурс на 1000 подписчиков на канале Просто Код Обещанный конкурс в связи с 1000 подписчиков на канале Просто Код объявляю открытым! Долго думал, как его организовать и провести, наконец мысли сошлись в единый паззл. Условия конкурса Принять участие могут только подписчики канала Просто Код, данный пост будет доступен только им. Так как Дзен не позволяет получать данные о подписчиках, то…
Ввод, вывод и потоки
Не будем углубляться сильно в теорию (для этого есть учебники и справочники), а просто примем за данность следующие моменты:
- ввод — данные, которые поступают от пользователя в систему при помощи клавиатуры.
- вывод — данные, которые поступают от системы пользователю при помощи терминала и монитора.
Кажется, что все пока просто, верно? Ввод и вывод распределяются между тремя стандартными потоками: stdin (standard input или стандартный ввод), stdout (standard output или стандартный вывод) и stderr (standard error или стандартная ошибка). Также каждый поток пронумерован: 0 (stdin), 1 (stdout) и 2 (stderr). Стандартный вывод используется командами только для считывания данных, остальные две (1 и 2) можно использовать только для их записи.
Understanding Standard I/O on Linux
Improve your Linux command-line workflow by piping multiple commands together using standard I/O.
Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.
As you use Linux, you may come across references to «standard I/O,» or «standard input,» «standard output,» and «standard error.» What do these terms mean?
Standard Input
Standard input is a term for the input that a command-based program receives. In interactive use, it is normally from the keyboard, but as you’ll see later, it can also come from a file.
While the keyboard these days is usually plugged directly into the machine, when text terminals were more common, standard input was taken from the terminal keyboard connected to a central minicomputer or mainframe. Modern Linux systems use terminal emulators or the system console for standard input.
Standard Output
Standard output, like standard input, is where a program will send its text output. Again, this is typically a terminal emulator on modern systems but in the past was also on physical terminals, either with CRT screens or printed on paper using teletypes.
Teletype terminals were more common when Linux’s predecessor, Unix, was being developed at Bell Labs in the late 1960s and early 1970s.
Like standard input, you can also redirect standard output to a file.
Standard Error
Standard error is usually used for any error messages a program may generate. As with standard output, it is usually displayed on the screen but can also be redirected to a file or to a block device like /dev/null.
How to Redirect Input and Output on Linux
One of the most powerful features of Linux and Unix systems is the ability to redirect input and output to files and other programs.
The most widely used method is to send the output from one command to another, or a «pipeline.» For example, to see how many Linux commands have «sh» in their name, you can pipe the output of the ls command with grep.
To redirect the output from a command to a file, use the > operator. For example, to send the output of the ls command into a file name filelist:
The >> operator appends the output to an existing file or creates it if it doesn’t exist. To prevent accidentally overwriting a file, you can set the «noclobber» option in Bash:
Of course, you can just use cat and specify the file path as an argument, but this is just an example.
You can redirect standard error using a file descriptor, or a number that stands for one of the forms of standard I/0. With file descriptors, 0 is standard input, 1 is standard output, and 2 is standard error. The syntax in Bash is [file descriptor]>. It’s useful to redirect standard error to /dev/null to get rid of errors:
You can redirect both standard output and input at once with &>, which is useful if you need to send an email or forum post describing a problem you’re having with a program:
Standard I/O Works Everywhere
Even with the graphical environments available today, standard I/O remains important because it’s still the universal interface, from desktop to server to mobile, being based on ASCII text.