Shell—输入输出重定向

大多数 UNIX 系统命令从你的终端接受输入并将所产生的输出发送回​​到您的终端。一个命令通常从一个叫标准输入的地方读取输入,默认情况下,这恰好是你的终端。同样,一个命令通常将其输出写入到标准输出,默认情况下,这也是你的终端。

输出重定向

有两种方式

  • [root@localhost ~]# command1 > file1       会覆盖文件原来内容
  • [root@localhost ~]# command1 >> file2     不会覆盖文件原来内容,追加到文件末尾
[root@localhost ~]# cat /etc/passwd | grep "root" > test.sh
[root@localhost ~]# cat /etc/passwd | grep "root" >> test.sh

输入重定向

和输出重定向一样,Unix 命令也可以从文件获取输入。这样,本来需要从键盘获取输入的命令会转移到文件读取内容。

语法:[root@localhost ~]# command1 < file1

注意:输出重定向是大于号(>),输入重定向是小于号(<)。

[root@localhost ~]# wc -l /etc/passwd
[root@localhost ~]# wc -l < /etc/passwd
[root@localhost ~]# grep "root" < /etc/passwd

注意:上面三个例子的结果不同:第一个例子,会输出文件名;后二个不会,因为它仅仅知道从标准输入读取内容。

同时替换输入和输出

语法:[root@localhost ~]# command1 < infile > outfile

执行command1,从文件infile读取内容,然后将输出写入到outfile中。

[root@localhost ~]# wc -l </etc/passwd >test

重定向深入讲解

一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件:

  • 标准输入文件(stdin): stdin的文件描述符为0,Unix程序默认从stdin读取数据。
  • 标准输出文件(stdout):stdout 的文件描述符为1,Unix程序默认向stdout输出数据。
  • 标准错误输出文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息。

默认情况下,command > file 将 stdout 重定向到 file,command < file 将stdin 重定向到 file。

# 将 stderr 重定向到 file 文件
[root@localhost ~]# command 2 > file

# 将 stderr 追加到 file 文件末尾
[root@localhost ~]# command 2 >> file

# 将 stdout 和 stderr 合并后重定向到 file 文件
[root@localhost ~]# command > file 2>&1
[root@localhost ~]# command >> file 2>&1

# 将 stdin 和 stdout 都重定向。command 命令将 stdin 重定向到 file1,将 stdout 重定向到 file2。
[root@localhost ~]# command < file1 > file2

/dev/null 文件

/dev/null 是一个特殊的文件,写入到它的内容都会被丢弃;如果尝试从该文件读取内容,那么什么也读不到。但是 /dev/null 文件非常有用,将命令的输出重定向到它,会起到"禁止输出"的效果。

# 如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到 /dev/null:
[root@localhost ~]# command > /dev/null

# 如果希望屏蔽 stdout 和 stderr,可以这样写:
[root@localhost ~]# command > /dev/null 2>&1

https://www.runoob.com/linux/linux-shell-io-redirections.html

原文地址:https://www.cnblogs.com/liuhaidon/p/11881324.html