File descriptors and redirection

File descriptor

File descriptors: Decide where to read input and where to write output and errors

$ls -l /dev/std*

  • 0: stdin
  • 1: stdout
  • 2: stderr

Output redirection

  • cmd [1|2]> file: Overwrites the source file
  • cmd [1|2]>> file: Adds the value. If no value is added, the value is added
  1. No automatic recursive path completion
  2. [1 | 2], the file descriptor (stdin | stderr), default is1, and>There is no space between

Two common uses:

  • $ ls > outfile 2>&1Redirect stdout and stderr together tooutfile:

1 omits, 2 redirects to the file 1 points to

  • cmd &> file: redirects 0,1,2 to file (&On behalf of0 and 1 & 2)

Using &> may generate some useless information in the text file. It is not normally used

Input redirection (<) :

$tr 'a-z' 'a-z' < w.txt > u.txt # In u # 0 -> w.txtCopy the code

Pipeline operation

|: pipeline

$cmd1 | cmd2: cmd1 output redirection for cmd2 input.

Using the pipe symbol to combine the two commands is equivalent to using the pipe joint to connect the faucet to the high-pressure water gun. It can also be used to send the water from the faucet to the hot water stove for heating and then to the high-pressure water gun. Using the pipe joint, the three existing normal operating systems can be combined into a new and more powerful system.

Work according to users $$who | wc - l cat/etc/passwd | wc - show the number of registered users $ls - lF l/bin | more displays the ls a lot of information with more (pages)Copy the code

| xargs: converts the data imported by the pipeline into the input parameters of the following command

$cat bd. TXT a.t xt b.t xt c.t xt $cat bd. TXT | xargs rm -f # delete a.t xt, b.t xt, c.t xtCopy the code

|tee: Command shunt output: (T-pipe)

Input the output of the previous command directly to the latter, while saving the results of the previous command to a file.

The function of the tee command is to copy the standard input to each specified file and standard output.

T – pipe concept from the life of the water pipe T – joint. A T-joint was connected to a pipe valve in a public toilet to divert “free” water, and to a high-pressure water pistol for washing cars and a flush toilet.

e.g.

$ cut -f1 -d: /etc/passwd | tee passwd.cut | sort -r | tee passwd.sort | more
Copy the code

This command needs to be explained:

Cut out the list of registered user names from /etc/passwd and save the data before and after the sort by adding the pipe and tee commands before and after the sort -r command to passwd.cut and passwd.sort files, respectively.

  • The tee passwd.cut command stores the piped data to the passwd.cut file, and also pipes the data to the next command for processing: sort -r to sort backwards.

  • The tee passwd.sort command stores the piped data (user name in reverse order) into the passwd.sort file. It also pipes the data to the next command for processing: the more command displays the data in pages.