Article directory
1. Standard input and standard output
There are three standard input and output in linux, namely STDIN, STDOUT, STDERR, and the file descriptors are 0, 1, and 2 respectively.
When the command is run, the process started by the command will automatically open the three reserved file descriptors.
As shown below
Everything is a file in Linux, including input and output, where:
- 0 means standard input, and the corresponding file descriptor is /proc/self/fd/0.
- 1 means standard output, and the corresponding file descriptor is /proc/self/fd/1.
- 2 Standard error, the corresponding file descriptor is /proc/self/fd/2.
These file descriptors can be used to control the input and output of command programs or scripts.
The meaning of our commonly used commands
2>&1
is to redirect standard error to standard output, that is, to specify standard output and standard error as the same output path.
2. Redirection
1. Definition
When the shell executes a command, it can modify the input source of standard input and the target location of standard output. This function is called redirection.
When redirecting, the syntax of n>file indicates that the output of the file descriptor n is redirected to the file file. If n is omitted, the file descriptor defaults to 1, so > redirects standard output.
2. Output redirection
The destination for standard output usually points to the terminal screen. The destination of standard output can be modified using the > symbol .
Example 1:
For example, the following example will redirect the output of the ps command to the result.txt file.
$ ps > result.txt ←----- 由于已经重定向到 result.txt 文件,所以屏幕上不会输出任何内容
$ cat result.txt
PID TTY TIME CMD
10745 pts/0 00:00:00 bash
10873 pts/0 00:00:00 ps
Example 2:
The execution result of the echo command will be redirected to the hello.txt file.
$ echo hello > hello.txt
$ cat hello.txt
hello
Note:
Redirection can be implemented as long as the command can output the execution result to standard output.
3. Redirection of standard error output
To redirect error messages from standard error, use the 2> symbol.
Example: The standard error output of the ls command will be redirected to the error.txt file.
$ ls /xxx 2> error.txt
$ cat error.txt
ls: 无法访问'/xxx': 没有那个文件或目录
4. Input redirection
Standard input can also be redirected like standard output.
Take the tr command as an example:
The tr command is a command for replacing character strings, and its syntax is tr 待替换的字符串 被替换后的字符串
.
tr b B
abc'
aBc'
my book
After inputting some content from the keyboard, the tr command will replace the input content in line units and output the replaced result. To exit the tr command, use Ctrl + D to end the input state.