Linux输入输出重定向

本文最后更新于:2025年6月25日 上午

标准输入、标准输出、标准错误

  • STDIN,文件描述符:0;标准输入,默认从键盘读取信息;

  • STDOUT,文件描述符:1;标准输出,默认将输出结果输出至终端;

  • STDERR,文件描述符:2;标准错误,默认将输出结果输出至终端

常用重定向命令

将命令的标准输出重定向到文件中

1
SomeCommand > SomeFile.txt  

将命令的标准输出重定向、追加到文件中

1
SomeCommand >> SomeFile.txt

将命令的标准输出、标准错误重定向到文件中

1
SomeCommand &> SomeFile.txt  

将命令的标准输出、标准错误重定向、追加到文件中

1
SomeCommand &>> SomeFile.txt  

使用tee命令,将命令的标准输出、标准错误重定向到文件中

1
SomeCommand 2>&1 | tee SomeFile.txt

来自Stack Overflow的表格:(n.e.表示不存在)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
          || visible in terminal ||   visible in file   || existing
Syntax || StdOut | StdErr || StdOut | StdErr || file
==========++==========+==========++==========+==========++===========
> || no | yes || yes | no || overwrite
>> || no | yes || yes | no || append
|| | || | ||
2> || yes | no || no | yes || overwrite
2>> || yes | no || no | yes || append
|| | || | ||
&> || no | no || yes | yes || overwrite
&>> || no | no || yes | yes || append
|| | || | ||
| tee || yes | yes || yes | no || overwrite
| tee -a || yes | yes || yes | no || append
|| | || | ||
n.e. (*) || yes | yes || no | yes || overwrite
n.e. (*) || yes | yes || no | yes || append
|| | || | ||
|& tee || yes | yes || yes | yes || overwrite
|& tee -a || yes | yes || yes | yes || append
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
tee

Read from standard input and write to standard output and files (or commands).
More information: https://www.gnu.org/software/coreutils/tee.

- Copy standard input to each file, and also to standard output:
echo "example" | tee path/to/file

- Append to the given files, do not overwrite:
echo "example" | tee -a path/to/file

- Print standard input to the terminal, and also pipe it into another program for further processing:
echo "example" | tee /dev/tty | xargs printf "[%s]"

- Create a directory called "example", count the number of characters in "example" and write "example" to the terminal:
echo "example" | tee >(xargs mkdir) >(wc -c)

Linux输入输出重定向
http://gls.show/p/5da01755/
作者
郭佳明
发布于
1970年1月1日
许可协议