Bash output redirection. Redirecting to multiple pins. Standard input from file

By reassigning I / O devices, one program can direct its output to the input of another, or intercept the output of another program using it as its input. Thus, it is possible to transfer information from process to process with minimal program overhead. In practice, this means that for programs that use standard input and output devices, the operating system allows:

  • output program messages not to the screen (standard output stream), but to a file or printer (output redirection);
  • read input data not from the keyboard (standard input stream), but from a prepared file (input redirection);
  • Pass messages from one program as input to another (pipelining or command composition).

From command line these possibilities are realized as follows. In order to redirect text messages displayed by any command from the command line to text file, you need to use the construction command> filename. If the file specified for output already existed, then it is overwritten (the old content is lost), if it did not exist, it is created. It is also possible not to recreate the file, but to append the information output by the command to the end of the existing file. To do this, the output redirection command must be specified like this: command >> filename... Using the symbol< можно прочитать входные данные для заданной команды не с клавиатуры, а из определенного (заранее подготовленного) файла: команда < имя_файла

Command line input / output redirection examples

Here are some examples of I / O redirection.

1. Conclusion of results ping commands to file ping ya.ru> ping.txt

2. Adding help text for XCOPY commands to copy.txt file: XCOPY /? >> copy.txt

If necessary, error messages (standard error stream) can be redirected to a text file using the command 2> filename In this case, the standard output will be printed to the screen. It is also possible to output informational and error messages to the same file. This is done as follows: command> filename 2> & 1

For example, the following command redirects standard output and standard error to copy.txt: XCOPY A: \ 1.txt C:> copy.txt 2> & 1

Three directions of I / O are dedicated - standard input, output, and error stream ( stdin, stdout, stderr ). By default, all three streams are associated (associated) with the terminal. In this case, the program displays all its messages, including errors, to the terminal. Shell allows you to redirect these standard streams, set I / O and stream concatenation.

Redirecting I / O streams.

> file Redirecting standard output to a file file

>> file -Redirecting the standard output stream to a file file appended to the end of the file.

-receiving the standard input stream from a file file.

prog1 | prog2 -Passing the output stream of the program prog1 to the input stream of the program prog2.

n> file file.

n >> file -Redirect standard stream with descriptor n to file file appended to the end of the file.

n> & m -Combining streams with descriptors n and m .

$ prog1> / dev / null 2> & 1

/ dev / null is a pseudo device that destroys the stream directed into it.

Transferring the output stream of one program to the input stream of another is a common practice. For example:

$ gzip -d archive.tar.gz | tar –xf

This is where the file is unzipped archive.tar.gz packed with two archivers. Output stream from utility gzip passed to the input stream to the utility tar ... Similarly, the same operation could be performed differently:

$ gzip -d archive.tar.gz

$ tar -xf archive.tar

Since the language Bourne Shell is a procedural programming language, in it, as in other similar languages, there are operators that allow you to control the sequence of command execution. The necessary operator is to check a certain condition, depending on the fulfillment of which the further course of the program is determined. This operator is the command test. This command checks the fulfillment of a certain condition. The team test there are two call options:

test condition

[ condition ]

It should be noted that there must be spaces between the parenthesis and the condition, otherwise Shell will not be able to recognize "[" as a command test ... On successful completion test returns "0" .

File validation conditions:

-f file File "file" is a regular file.

-d file File " file " is a directory.
-c file File "file" is a special file.
-r file File "file" has read permission.

-w file File "file" has write permission.

-x file File "file" has permission to execute.

-s file File "file" not empty.

String validation conditions:

string1 = string2 Strings string1 and string2 match.

string1! = string2 Strings string1 and string2 do not match.

-n string1 Line string1 exists.

-z string1 Line string1 does not exist.

Conditions for integer operations:

x -eq y x equals y

x -ne y x is not equal to y

x -gt y x is greater than y

x -ge y x is greater than or equal to y

x -lt y x is less than y

x -le y x is less than or equal to y

In this case, the command test treats strings exactly as integers. An empty string also corresponds to a null value.

Logical operations in context test

! (not) Logical "NOT"

-o (or) Logical "OR"

-a (and) Logical "AND"

Conditional operator "if"

The general view of using the if conditional statement is as follows:

if<условие>

then<список команд>

[elif<условие>

then<список> ]

Expressions in square brackets are optional. Those. you can imagine the most common "cut" modification of the conditional operator:

if<условие>

then<список команд>

In this case, if <условие> executed (exit code 0) then executed <список команд>. Otherwise <список команд> skipped.

Selection operator case

In general, the syntax of the operator case as follows:

case<строка>in

Template 1)

........

Template2)

........

........

Meaning <строка> matches the patterns, in order. If a match is found, then the commands of the corresponding section are executed. It should be noted that templates allow the use of masks. If no match was found, then commands from the section with the "*" pattern are executed (similarly default selector switch v WITH ).

As an example, we will give a piece of the initialization script. BSD UNIX ... Here the variables (inetd_enable and inetd_flags) were obtained from another file ( rc.conf).

... /etc/rc.conf

case ($ inetd_enable) in

)

if [-x / usr / sbin / inetd]; then

/ usr / sbin / inetd $ inetd_flags

fi

;;

esac

Enumerated loop operator for

Operator syntax for

for<имя>

<список команд>

The section in square brackets may be missing. Operator for ensures that the loop is executed as many times as there are words in the list of values. In this case, the variable <имя> takes consecutively the values ​​of words from the list. The list itself can be formed from the output of other commands. If there is no list, then <имя> accepts values ​​passed as positional parameters to the script.

Loop operator with true condition while

Operator syntax while generally has the following structure:

while<условие>

<список команд>

Operator while preferred when the list of parameter values ​​is not known in advance. The list of commands will be executed in a loop as long as the condition remains true. When entering the loop for the first time, the condition must be met.

Loop operator with false condition until

Operator syntax until generally has the following structure:

until<условие>

<список команд>

The list of commands will be executed in a loop as long as the condition remains false. When entering the loop for the first time, the condition should not be met. It should be noted that the loop condition is checked for falsehood after each one, incl. and the first executed command in the loop.

Basic commands UNIX OS to work with files

1. Team pwd.

Syntax: pwd .

Description: The command displays the name of the current directory for the running shell.

Exercise 1.

Use the pwd command to define your home directory.

Reflect the team and the result of its work in the report.

2. Team man.

Syntax: man name.

The name is the name of the command, utility, system call, library function, file we are interested in.

Description : UNIX MANUAL - guide operating system UNIX. Information from there is available online using the utility man .

Task 2.

Use the man utility to view information about the pwd command.

Write down briefly information about the team in the report (in Russian).

3. Team cd.

Syntax: cd directory_name.

Description: This is a command to change the current directory. Directory_name is the full or relative name of the directory you want to make the current directory.

cd without parameters will make your home directory current.

Task 3.

Make the current directory one level up. Check it out, then go back to your home directory. Check the directory change.

Record the execution of the commands performed in the report.

4. Team ls.

Syntax: ls directory_name

Description: command to view the contents of the specified directory.

ls without parameters prints a list of files from the current directory.

The resulting list will not include files whose names begin with the “ . ”- files created by various system programs for their own purposes. Look full list files can be specified in the command ls key "-a",

those. ls -a directory_name

File permissions

With every file in UNIX OS associated with a 12-bit word called "permissions" to the file.

The least significant 9 bits of this word are grouped into three groups of three bits; each group specifies the permissions for the owner of the file, for his group, and for all other users. Three bits in each group are responsible for the right to read, request and use the file.

To find out the permissions for a particular file, you can use the command

, for example:

> ls -l / bin / cat

The group of characters at the beginning of the line -rwxr-xr-x shows the file type (the first character; minus means that we are dealing with an ordinary file, the letter d would mean a directory, etc.) and access rights, respectively, for the owner (in this case rwx , i.e. read, write and execute), group and everyone else (in this case r-x , i.e. no write rights). So the file / bin / cat available to any user for reading and execution, but only the user can modify it root (i.e. administrator).

You can write the word of file access rights in the form of an octal number (3 characters - an octal digit), three-digit (owner, group, other users), each character in this three-digit octal number is formed as the sum of rights: 4- read rights, 2- rights to record, 1 - to use (from the binary triad): (111) 2 =2 0 +2 1 +2 2 =(1+2+4) 10 .

For example, 7 = 1 + 2 + 4 Þ rights rwx

4 2 1

6 = 0 + 2+ 4 Þ rights rw- -

4 2 0

In the three-digit number of the assignment of rights: 744 all rights are defined for the owner, read-only for the group, and read-only for other users.

To use file permissions, use the command chmod , which allows you to set new access rights in the form of an octal number, for example:

$ chmod 744 filel.c.

Task 4.

a) For complete information on the ls command, use the man utility. Redirect the command output to some text file.

b) Look at the complete contents of the current directory and redirect this output to a text file as well.

c) Using the command ls -l<имя_файла> print information about the access rights to the text file with which you worked in step 4b, then redirect this information to the same text file. Explain your conclusion.

5. Team cat.

I / O redirection.

To view the contents of a small text file on the screen, you can use the command:

cat File name

Attention! Do not try to browse the contents of the directory and binaries this way.

It is convenient to view a large test file with the command more (for a description of use, see UNIX MANUAL ). Why is the command inconvenient here cat ?

In a team cat multiple filenames can be specified:

сat file1 file 2 ... file N

the contents of all files in a row will be displayed on the screen.

You can redirect the output to some file:

сat file 1 file 2> results_file

Redirecting output from the standard output stream (screen) to a file is standard for all commands. To redirect standard input (from the keyboard), for example, to take data for a program from a file, use the “<”.

сat> new_file - will create a new text file with the content you enter from the keyboard.

Abort the data entry process -

Task 5.

Create a new text file with cat and view its contents. Redirect the output from the standard stream to another file, the name of which you enter from the keyboard, and verify that the operation was performed correctly.

6. The simplest commands for working with files : cp, rm, mkdir, mv

To create a new directory, use the command:

mkdir directory_name

To copy the contents of one file to another, use the command:

cp file_source file_destination.

Command

cp file 1 file 2…. file N destination directory

serves to copy a file or files into an existing directory with the name of the destination_directory under their own names. Instead of the names of the copied files, you can use their templates. Templates are specified using metacharacters:

* - matches all character strings, including the empty one.

All single letters

[…] - matches any character enclosed in brackets. A pair of characters separated by a minus specifies the range of characters.

Command

cp - r dir_source dir_destination

serves to recursively copy one directory (source_dir) to a new directory (destination_directory).

Patterns can be used instead of names in copy commands.

Command

rm file 1 file 2…. file N

allows you to remove 1 or more regular files from the current directory.

Templates can be used instead of names. If you want to delete one or more directories along with their contents (recursive deletion) in the command rm use the key -r

Rm-r dir 1 dir 2

Rename command:

mv source_name destination_name

The file named source_name renames to a file named target_name. In this case, before the command is executed, the file with the name target_name should not exist.

Task 6.

Create new directory inside your home. Organize there a small test file with two lines of content:

“I study working in UNIX OS

I will organize a script. "

Copy the contents of this file to another one with the same name, but in the / home directory. Delete the originally created file from your directory if copying was successful. Check the contents of the used directories and files.

Task 7.

1). When you have mastered working interactively with the simplest UNIX OS commands, use the Kwriter editor to create a script with a script corresponding to the sequential execution:

Task 3,

Task 4B, 4B,

Task 5,

Task 6.

In task 6, do not forget to check programmatically if the file was copied successfully, with the output on the display screen text messages and the contents of the corresponding directories.

It is necessary that in command file the competent issuance of requests for data entry from the keyboard was organized using the command: $ echo - n “request text”.

2). Save the script with the name Myscript1, run it with the command

sh Myscript1

enter the requested information and check the results.

3). Make a report on the completed laboratory work, which should reflect both your work in interactive mode and with the script, including the script text (with comments) and the results obtained on the screen and in files.

System calls getuid and getpid

Find out the identifier of the user who launched the program for execution - UID and the id of the group it belongs to , -GID can be done using system calls getuid () and getpid () by applying them inside this program.

System call prototypes:

#include

#include

uid_t getuid (void);

gid_t getgid (void);

Task 8.

Write, compile, and run a program that prints the ID of the user who started the program and the ID of his group.

Include the program with the results in the report.

Control questions

1. The concept of a file in UNIX OS ... What is a home directory?

2. What are the means of grouping teams Shell -interpreter? give examples of use.

3. How is I / O redirection done?

4. What is a command pipeline? give an example.

5. How means Shell perform arithmetic operations on Shell -variable?

6. What are the rules for generating filenames?

7. How is command substitution performed?

8. How to interpret a string cmd1 & cmd2 & ?

9. How to interpret a string cmd1 && cmd2 & ?

10. How to interpret a string cmd1 || cmd2 & ?

11. As in UNIX file permissions defined? What team can you watch for specific file?

12. How to determine the identifier of the user who launched the program and the identifier of his group?

Laboratory work № 3.

Processes in the operating system UNIX.

purpose of work

Learn to create processes and master changing the user context of processes using system calls used in programs in the language WITH, v UNIX OS.

1. Examine the organization of processes in UNIX : process concept, process context, process life cycle, process identification, hierarchical structure processes. Write to WITH and debug the program according to task 1.

2. Become familiar with creating a process in UNIX , with the organization of the completion of the process. Write and debug a program (language WITH ) in accordance with Task 2, include it in the report.

3. Examine the parameters of the function main () in language WITH , Environment Variables and command line arguments. Write a program in the language WITH in accordance with Task 3, debug and include it in the report along with the results.

4. Examine the family of functions for organizing a system call exec ().

5. Write a program in the language WITH in accordance with the variant of Task 4 given by the teacher, debug the program and demonstrate the results to the teacher. Include the program with the results in the report.

6. Defend the teacher's work by answering control questions.

1403

Redirection "2> & 1", "> / dev / null" or Unix output streams (bash / sh)

Your rating: a masterpiece excellent very good good normal Didn't read tolerantly mediocre bad very bad not read

Output streams

Script messages are output to well-defined streams - output streams. Thus, what we output through

echo "Hello, world!"

It is not just displayed on the screen, but, from the point of view of the system, and specifically - from the sh and bash command interpreters - it is output through a specific output stream. In the case of echo, stream number 1 (stdout) with which the screen is associated.

Some programs and scripts also use a different output stream - numbered 2 (stderr). They output error messages to it. This allows normal information and error messages to be taken from streams separately and sent and processed separately.

For example, you can block the withdrawal information messages leaving only error messages. Or direct the output of error messages to separate file for logging.

What is "> somefile"

This entry in Unix (in the bash and sh interpreters) indicates the redirection of output streams.

In the following example, we will redirect all informational (normal) messages from the ls command to the file myfile.txt, thus getting just a list of ls in this file:

$ ls> myfile.txt


In this case, after pressing Enter, you will not see anything on the screen, but the file myfile.txt will contain everything that should have been displayed on the screen.

However, let's make a knowingly erroneous operation:

$ ls / masdfasdf> myfile.txt


And what will happen? Because the masdfasdf directory at the root of the file system does not exist (I suppose - what if you have one?), then the ls command will generate an error. However, it will throw out this error not through the usual stdout (1) stream, but through the stderr (2) error stream. And redirection is only specified for stdout ("> myfile.txt").

Because we did not redirect the stderr (2) stream anywhere - an error message will appear on the screen and will NOT appear in the myfile.txt file

Now let's run the ls command so that informational data is written to the file myfile.txt, and error messages are written to the file myfile.err, and nothing appears on the screen at runtime:

$ ls> myfile.txt 2> myfile.err


This is where we first see the stream number being specified as a redirect. The entry "2> myfile.err" indicates that stream number 2 (stderr) should be redirected to the file myfile.err.

Of course, we can send both streams to the same file or to the same device.

2>&1

You can often find such an entry in scripts. It means: "Stream number 2 redirect to stream number 1", or "Stream stderr - send through the stream stdout". Those. we send all error messages through the stream through which normal, non-error messages are usually printed.

$ ls / asfasdf 2> & 1


And here's another example, in which all messages are redirected to the myfile.txt file:

$ ls / asfasdf> myfile.txt 2> & 1


In this case, all messages, both about errors and ordinary ones, will be written to myfile.txt, because we first redirected the stdout stream to a file, and then indicated that errors should be dumped into stdout - respectively, into the file myfile.txt

/ dev / null

However, sometimes we just need to hide all messages - without saving them. Those. just block the output. For this purpose serves virtual device/ dev / null. In the following example, we will direct all the output of the usual messages of the ls command to / dev / null:

$ ls> / dev / null


Nothing will be displayed on the screen except error messages. And in the next example, error messages will be blocked:

$ ls> / dev / null 2> & 1


Moreover, this record is equivalent to a record of the form:

$ ls> / dev / null 2> / dev / null


And in the following example, we will only block error messages:

$ ls 2> / dev / null

Note that you can no longer specify "2> & 1" here, since stream (1) is not redirected anywhere, and in this case, error messages will be trivially dumped on the screen.

Which comes first - an egg or a chicken?

I will give you 2 examples here.

Example 1)

$ ls> / dev / null 2> & 1


Example 2)

$ ls 2> & 1> / dev / null


It looks like the amount does not change from the rearrangement of the places of the words. But the order of the redirection pointers matters!

The point is that interpreters read and apply redirects from left to right. And now we will analyze both examples.

Example 1

1) "> / dev / null" - we are sending stream 1 (stdout) to / dev / null. All messages entering stream (1) will be directed to / dev / null.

2) "2> & 1" - we redirect stream 2 (stderr) to stream 1 (stdout). But since stream 1 is already associated with / dev / null - all messages will end up in / dev / null anyway.

Result: the screen is blank.

Example 2

1) "2> & 1" - we redirect the stderr (2) error stream to the stdout (1) stream. Moreover, since stream 1 is associated with the terminal by default - we will successfully see error messages on the screen.

2) "> / dev / null" - and already here we redirect stream 1 to / dev / null. And we will not see regular messages.

Result: we will see error messages on the screen, but we will not see normal messages.

Conclusion: first redirect the stream, and then link to it.

One of the most interesting and useful topics for system administrators and new users who are just starting to understand how to work with the terminal is Linux I / O redirection. This feature of the terminal allows you to redirect the output of commands to a file, or the contents of a file to command input, combine commands together, and form command pipelines.

In this article, we will look at how I / O redirection is performed in Linux, what operators are used for this, and also where all this can be applied.

All the commands we execute return three kinds of data to us:

  • The result of command execution, usually text data requested by the user;
  • Error messages - inform about the process of command execution and unforeseen circumstances;
  • The return code is a number that allows you to evaluate whether the program worked correctly.

In Linux, all substances are considered files, including input streams linux output- files. Each distribution has three main stream files that programs can use, these are defined by the shell and identified by the file descriptor number:

  • STDIN or 0- this file is associated with the keyboard and most commands get data to work from here;
  • STDOUT or 1- this is standard output, here the program sends all the results of its work. It is associated with the screen, or more precisely, with the terminal in which the program is running;
  • STDERR or 2- all error messages are output to this file.

I / O redirection allows you to replace one of these files with your own. For example, you can force the program to read data from a file into file system, not the keyboard, you can also output errors to a file, not to the screen, etc. All this is done using symbols "<" and ">" .

Redirect output to a file

Everything is very simple. You can redirect the output to a file using the> symbol. For example, let's save the output of the top command:

top -bn 5> top.log

The -b option makes the program run in non-interactive batch mode, and n - repeats the operation five times to get information about all processes. Now let's see what happened with cat:

Symbol ">" overwrites the information from the file if there is already something there. To add data to the end use ">>" ... For example, redirect the output to a linux file else for top:

top -bn 5 >> top.log

By default, the standard output file descriptor is used for redirection. But you can specify this explicitly. This command will give the same result:

top -bn 5 1> top.log

Redirect errors to file

To redirect error output to a file, you need to explicitly specify the file descriptor you want to redirect. For errors, this is number 2. For example, when trying to access the superuser directory, ls will give an error:

You can redirect standard error to a file like this:

ls -l / root / 2> ls-error.log
$ cat ls-error.log

To add data to the end of the file, use the same symbol:

ls -l / root / 2 >> ls-error.log

Redirect standard output and errors to a file

You can also redirect all output, errors, and standard output to a single file. There are two ways to do this. The first one, the older one, is to pass both descriptors:

ls -l / root /> ls-error.log 2> & 1

First, the output of the ls command will be sent to the ls-error.log file using the first redirection character. Further, all errors will be sent to the same file. The second method is simpler:

ls -l / root / &> ls-error.log

You can also use append instead of overwrite:

ls -l / root / & >> ls-error.log

Standard input from file

Most programs, except for services, receive data for their work through standard input. By default, standard input expects data from the keyboard. But you can force the program to read data from a file using the operator "<" :

cat

You can also immediately redirect the output to a file too. For example, let's re-sort the list:

sort sort.output

Thus, we redirect the linux input / output in one command.

Use of tunnels

You can work not only with files, but also redirect the output of one command as the input of another. This is very useful for performing complex operations. For example, let's display five recently changed files:

ls -lt | head -n 5

With the xargs utility, you can combine commands so that standard input is passed to parameters. For example, let's copy one file into several folders:

echo test / tmp / | xargs -n 1 cp -v testfile.sh

Here, the -n 1 option specifies that only one option should be substituted for one command, and the -v option to cp allows you to display detailed information about movements. Another command useful in such cases is tee. It reads data from standard input and writes to standard output or files. For example:

echo "Test tee working" | tee file1

Combined with other commands, these can be used to create complex instructions from multiple commands.

conclusions

In this article, we covered the basics of redirecting Linux I / O streams. Now you know how to redirect output to a linux file or output from a file. It is very simple and convenient. If you still have questions, ask in the comments!

In order to write data to file or read them from there, the process must first open this file (when opening for writing, it may have to first create it). In this case, the process receives descriptor(descriptor) of an open file is a number unique for this process, which it will use in all write operations. The first open file will receive a handle, the second 1, and so on. When finished with the file, the process closes it, and the descriptor is freed and can be reused. If the process ends without closing the files, the system does it for it. Strictly speaking, only in the operation of opening a descriptor is it indicated which file will be used. Both regular files and hole files (most often terminals) are used as a "file", and channels described in the section Pipeline..Conveyor. Further operations - read, write and close, work with the descriptor, as with data stream, but where exactly this stream leads, it does not matter.

Every Linux process gets on startup three"File" opened for it by the system. The first one (handle) is open to reading, this is standard input process. It is with standard input that all read operations work if they do not specify a file descriptor. The second (descriptor 1) is open for writing, it is stdout process. All write operations work with it, unless the file descriptor is explicitly specified in them. Finally, the third data stream (descriptor 2) is intended for printing diagnostic messages, it is called standard error output... Since these three descriptors are already open when the process starts, the first file opened by the process itself will most likely have descriptor 3.

Descriptor A descriptor for the data stream opened by the process. Descriptors are numbered starting from. When a new data stream is opened, its descriptor gets the smallest number that is not used at that moment. Three pre-opened descriptors: standard input (), stdout(1) and standard error output(2) are issued to the process at startup.

Copy mechanism surroundings, described in the lecture, implies, among other things, copying all open handles of the parent process to the child. As a result, both parent and child processes have the same data streams under the same descriptors. When it starts startup shell, all three previously opened descriptors are associated with terminal(more precisely, with a corresponding hole file like tty): the user enters commands from the keyboard and sees messages on the screen. Hence, any command run from the command shell will output to the same terminal, and any command run interactively(not in the background) - enter from there.

Standard output

Methodius has already come across the fact that some programs are able to output not only to the terminal, but also to a file, for example, info when specifying parametric key"-O" with the filename will output the manual text to a file instead of displaying it on the monitor. Even if the developers of the program do not provide such a key, Methodius also knows another way to save the output of the program in a file instead of displaying it on the monitor: put a ">" sign and indicate the file name after it. Thus, Methodius has already created short text files (scripts) using the cat utility (see the lecture Accessing Processes to Files and Directories).

$ cat> textfile This is the example file. ^ D $ ls -l textfile -rw-r - r-- 1 methody methody 23 Nov 15 16:06 textfile

Example 2... Redirecting standard output to a file

Of course, the use of the ">" symbol did not expand the capabilities of the cat utility itself. Moreover, cat in this example did not receive from shell no parameters: no ">" sign, no subsequent file name. In this case, cat worked as usual, not knowing (and not even interested!) Where the outputted data would go: on the monitor screen, in a file, or somewhere else. Instead of providing itself with the delivery of the output to the final destination (be it a person or a file), cat sends all the data to stdout(abbreviated - stdout).

The substitution of standard output is a shell task. In this example, the shell creates an empty file, the name of which is specified after the ">" sign, and the descriptor of this file is passed to the cat program at number 1 ( stdout). This is done very simply. In the chapter Accessing Files and Directories by Processes, you learned how to run commands from the shell. In particular, after executing fork (), two identical processes appear, one of which - the child - must run the command instead of itself (execute exec ()). So, before that he closes standard output (descriptor 1 is freed) and opens file (linked to first a free descriptor, i.e. 1), and the command being run does not need to know anything: its standard output has already been replaced. This operation is called redirecting standard output. In the event that the file already exists, the shell will rewrite it, completely destroying everything that was previously contained in it. Therefore, to continue writing data to the textfile, Methodius will need another operation - ">>".

$ cat >> textfile Example 1. ^ D $ cat textfile This is the file for examples. Example 1. $

Example 3... Non-destructive standard output redirection

Methodius got exactly the result he needed: he added data from the standard output of the next command to the end of an existing file.

Standard Output A stream of data opened by the system for each process when it starts up and intended for data output by the process.

Standard input

Similarly, to transfer data to the input to the program, you can use standard input(abbreviated - stdin). When working with the command line, standard input is the characters that the user enters from the keyboard. Standard input can be redirected using the shell by feeding data from a file to it. Symbol "< » служит для перенаправления содержимого файла на стандартный ввод программе. Например, если вызвать утилиту sort без параметра, она будет читать строки со стандартного ввода. Команда « sort < имя_файла"Will feed sort to the data from the file.

$ sort< textfile Пример 1. Это файл для примеров. $

Example 4... Redirecting stdin from a file

The effect of this command is exactly the same as the sort textfile command, the difference is that when you use "< », sort получает данные со стандартного ввода, ничего не зная о файле « textfile », откуда они поступают. Механизм работы shell в данном случае тот же, что и при перенаправлении вывода: shell читает данные из файла « textfile », запускает утилиту sort и передаёт ей на стандартный ввод содержимое файла.

It is worth remembering that the operation ">" destructive: it always creates a zero-length file. Therefore, for, say, sorting data in file sort must be applied sequentially < файл >new_file and mv new_file file... View command command< файл >same_file will just truncate it to zero length!

Standard input A data stream that is opened by the system for each process at the moment it starts, and is intended for data input.

Standard error output

As a first example and exercise on redirection, Methodius decided to write a manual on cat in his cat.info file:

$ info cat> cat.info info: Node entry (coreutils.info.bz2) cat invocation ... info: Completed. $ head -1 cat.info File: coreutils.info, Node: cat invocation, Next: tac invocation, Up: Output of entire files $

Example 5... Standard error output

Surprised Methodius discovered that, despite his instructions to send to the file, the two lines displayed by the info command still penetrated the terminal. Obviously, these lines did not make it to stdout because they do not directly relate to the manual that the program should output, they inform the user about the progress of the work: writing the manual to a file. For this kind diagnostic messages, as well as for messages about errors that occurred during the execution of the program, Linux provides standard error output(short for stderr).

Standard error output The data stream opened by the system for each process at the time it starts, and intended for diagnostic messages output by the process.

Using standard error output along with standard output allows you to separate the actual output of the program from various accompanying information, for example, by sending them to different files. Standard error output can be redirected in the same way as standard I / O by using the "2" character combination.

$ info cat> cat.info 2> cat.stderr $ cat cat.stderr info: Node entry (coreutils.info.bz2) cat invocation ... info: Completed. $

Example 6... Redirecting standard error output

This time nothing got to the terminal, the standard output went to the cat.info file, the standard error output went to cat.stderr. Instead of ">" and "2" Methodius could write "1>" and "2>". The numbers in this case indicate the numbers of the descriptors opened files. If some utility expects to receive open a descriptor with a number, say 4, then to run it necessarily you will need to use the combination "4>".

Sometimes, however, you want to combine standard output and standard error output in a single file, rather than separate them. The bash shell has a special sequence "2> & 1" for this. This means "direct the standard error output to the same place as the standard output":

$ info cat> cat.info 2> & 1 $ head -3 cat.info info: Entry of the node (coreutils.info.bz2) cat invocation ... info: Completed. File: coreutils.info, Node: cat invocation, Next: tac invocation, Up: Output of entire files $

Example 7... Combining stdout and stdout

In this example, the order of redirections is important: on the command line, Methodius first indicated where to redirect the standard output ("> cat.info") and only then ordered the standard error output to be sent there. Do it the other way around ("2> & 1> cat.info"), the result would be unexpected: only the standard output would get to the file, and diagnostic messages would appear on the terminal. However, the logic here is ironclad: at the time of the "2> & 1" operation, the standard output was connected to the terminal, which means that after Executing it will also associate standard error with the terminal. And the subsequent redirection of stdout to a file, of course, will not affect stdout in any way. The number in the construction "& number" is the number open descriptor. If the above utility that writes to the fourth descriptor were written in shell, it would use redirects like "> & 4". In order not to type the cumbersome construction "> file 2> & 1" in bash, abbreviations are used: "&> file" or, which is the same, "> & file".

Redirect to nowhere

Sometimes it is known in advance that some data output by the program will not be needed. For example, warnings from standard error output. In this case, you can redirect standard error output to hole file specially designed for destroying data - / dev / null. Everything that is written to this file will simply be thrown away and will not be saved anywhere.

$ info cat> cat.info 2> / dev / null $

Example 8... Redirect to / dev / null

Likewise, you can get rid of the standard output by sending it to / dev / null.

Did you like the article? To share with friends: