1. 重定向的基本概念
将原本应该输出到标准输出设备(显示器)的内容,改而输出到其他文件或设备上。
2. I/O重定向
#
列出/usr
目录中的文件信息,默认所产生的输出会显示在屏幕上
[root@localhost ~]# ls -l /usr/
total 176
drwxr-xr-x 2 root root 40960 Apr 11 11:19 bin
drwxr-xr-x 2 root root 4096 Oct 1 2009 etc
drwxr-xr-x 2 root root 4096 Oct 1 2009 games
drwxr-xr-x 50 root root 4096 Apr 11 10:21 include
drwxr-xr-x 6 root root 4096 Feb 23 2012 kerberos
drwxr-xr-x 99 root root 36864 Apr 11 11:19 lib
drwxr-xr-x 11 root root 4096 Apr 11 11:19 libexec
drwxr-xr-x 12 root root 4096 Apr 11 10:38 local
drwxr-xr-x 2 root root 12288 Apr 11 11:19 sbin
drwxr-xr-x 183 root root 4096 Apr 11 10:21 share
drwxr-xr-x 4 root root 4096 Feb 26 21:13 src
lrwxrwxrwx 1 root root 10 Feb 26 21:13 tmp -> ../var/tmp
drwxr-xr-x 3 root root 4096 Feb 26 21:15 X11R6
[root@localhost ~]# ls -l /usr/ > ls_usr.txt #
回车
[root@localhost ~]# #
注意到回车后并没有任何输出,因为输出被重定向到文件中
[root@localhost ~]# cat ls_usr.txt #
此文件内容和之前的输出一致
total 176
drwxr-xr-x 2 root root 40960 Apr 11 11:19 bin
drwxr-xr-x 2 root root 4096 Oct 1 2009 etc
drwxr-xr-x 2 root root 4096 Oct 1 2009 games
drwxr-xr-x 50 root root 4096 Apr 11 10:21 include
drwxr-xr-x 6 root root 4096 Feb 23 2012 kerberos
drwxr-xr-x 99 root root 36864 Apr 11 11:19 lib
drwxr-xr-x 11 root root 4096 Apr 11 11:19 libexec
drwxr-xr-x 12 root root 4096 Apr 11 10:38 local
drwxr-xr-x 2 root root 12288 Apr 11 11:19 sbin
drwxr-xr-x 183 root root 4096 Apr 11 10:21 share
drwxr-xr-x 4 root root 4096 Feb 26 21:13 src
lrwxrwxrwx 1 root root 10 Feb 26 21:13 tmp -> ../var/tmp
drwxr-xr-x 3 root root 4096 Feb 26 21:15 X11R6
标准输出追加重定向:>>
该符号用法和>完全一致,不同的只是如果指定的重定向文件存在且内容不为空,重定向并不会清空原文件内容,而是将命令的输出新增到原文件的尾部。在下面的例子中,先后将/usr和/tmp目录中列出的内容追加重定向append.txt文件。
[root@localhost ~]# ls -l /usr/ >> append.txt
[root@localhost ~]# ls -l /tmp/ >> append.txt
[root@localhost ~]# cat append.txt
total 176
drwxr-xr-x 2 root root 40960 Apr 11 11:19 bin
drwxr-xr-x 2 root root 4096 Oct 1 2009 etc
drwxr-xr-x 2 root root 4096 Oct 1 2009 games
drwxr-xr-x 50 root root 4096 Apr 11 10:21 include
drwxr-xr-x 6 root root 4096 Feb 23 2012 kerberos
drwxr-xr-x 99 root root 36864 Apr 11 11:19 lib
drwxr-xr-x 11 root root 4096 Apr 11 11:19 libexec
drwxr-xr-x 12 root root 4096 Apr 11 10:38 local
drwxr-xr-x 2 root root 12288 Apr 11 11:19 sbin
drwxr-xr-x 183 root root 4096 Apr 11 10:21 share
drwxr-xr-x 4 root root 4096 Feb 26 21:13 src
lrwxrwxrwx 1 root root 10 Feb 26 21:13 tmp -> ../var/tmp
drwxr-xr-x 3 root root 4096 Feb 26 21:15 X11R6
total 0
srwxr-xr-x 1 root root 0 Mar 1 11:27 gedit.root.903135227
srwxr-xr-x 1 root root 0 Mar 28 00:18 mapping-root