shell之路 Linux核心命令【第一篇】管道符与重定向
输出重定向
命令输出重定向的语法为:
command > file 或 command >> file
这样,输出到显示器的内容就可以被重定向到文件。果不希望文件内容被覆盖,可以使用 >> 追加到文件末尾
[root@hy ~]# who root tty1 2015-09-03 16:21 root pts/3 2015-09-03 19:09 (192.168.11.1) [root@hy ~]# who > output.txt [root@hy ~]# cat output.txt root tty1 2015-09-03 16:21 root pts/3 2015-09-03 19:09 (192.168.11.1)
输入重定向(<可省略)
command < file
[root@hy ~]# wc -l output.txt 2 output.txt [root@hy ~]# wc -l < output.txt
[root@hy ~]# cat < output.txt root tty1 2015-09-03 16:21 root pts/3 2015-09-03 19:09 (192.168.11.1) [root@hy ~]# cat output.txt root tty1 2015-09-03 16:21 root pts/3 2015-09-03 19:09 (192.168.11.1)
输入输出重定向深入
一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件:
- 标准输入文件(stdin):stdin的文件描述符为0,Unix程序默认从stdin读取数据。
- 标准输出文件(stdout):stdout 的文件描述符为1,Unix程序默认向stdout输出数据。
- 标准错误文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息
一般情况下,只默认将stdout重定向到文件
[root@hy ~]# ls /root/ > output.txt [root@hy ~]# cat output.txt anaconda-ks.cfg install.log install.log.syslog output.txt use
stderr 重定向到 file
command 2 > file 或 command 2 >> file
[root@hy ~]# l /root/ > output.txt -bash: l: command not found [root@hy ~]# cat output.txt [root@hy ~]# l /root/ 2> output.txt [root@hy ~]# cat output.txt -bash: l: command not found
stdout 和 stderr 合并后重定向到 file
command > file 2>&1 或 command >> file 2>&1
对 stdin 和 stdout 都重定向
[root@hy ~]# who > output.txt [root@hy ~]# cat output.txt root tty1 2015-09-03 16:21 root pts/3 2015-09-03 19:09 (192.168.11.1) [root@hy ~]# cat output.txt > hy.txt [root@hy ~]# cat < output.txt > hy1.txt [root@hy ~]# cat hy.txt root tty1 2015-09-03 16:21 root pts/3 2015-09-03 19:09 (192.168.11.1) [root@hy ~]# cat hy1.txt root tty1 2015-09-03 16:21 root pts/3 2015-09-03 19:09 (192.168.11.1)
Here Document
1.它的作用是将两个 delimiter 之间的内容(document) 作为输入传递给 command。
2.delimiter字符可自定义
语法:
command << delimiter document delimiter
实例
[root@hy ~]# wc -l << EOF > root tty1 2015-09-03 16:21 > root pts/3 2015-09-03 19:09 (192.168.11.1) > EOF 2
wc -l << EOF root tty1 2015-09-03 16:21 root pts/3 2015-09-03 19:09 (192.168.11.1) EOF
/dev/null文件
如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到 /dev/null:
command > /dev/null
如果希望屏蔽 stdout 和 stderr,可以这样写:
command > /dev/null 2>&1
谢谢