命令行是你的至交好友 -Part 3

重定向 Unix系统有一个非常强大的特性:因为所有资源都是文件,你可以将所有资源引用和将其从一个位置重定向到另一个位置。重定向的操作符<表示标准输入(stdin),>表示标准输出(stdout)。所以,如果你需要一个命令从键盘中读取信息,你可以进行如下操作:
$ someCommand <
但当要你的命令从一个文件中读取内容你要怎么做呢?你只要重定向这个文件到它的标准输入(stdin),如下:
$ someCommand < /your/file.txt
如果你要你的命令执行结果输出到一个文件,你可以使用>操作符。例如我们已经知道如何将一个目录中的文件列出:
csaba@csaba-pc ~/tmp/NetTuts/SecondDir $ ls -al
total 8
drwxr-xr-x 2 csaba csaba 4096 Feb 19 21:09 .
drwxr-xr-x 4 csaba csaba 4096 Feb 19 21:09 …
-rw-r–r-- 1 csaba csaba 0 Feb 19 21:09 aFile
-rw-r–r-- 1 csaba csaba 0 Feb 19 21:09 AnotherFile
csaba@csaba-pc ~/tmp/NetTuts/SecondDir $

你可以把使用如下命令将结果发送到一个文件:
csaba@csaba-pc ~/tmp/NetTuts/SecondDir $ ls -al > ./ThirdFile
ThirdFile的内容如下:
total 12
drwxr-xr-x 2 csaba csaba 4096 Feb 24 00:06 .
drwxr-xr-x 4 csaba csaba 4096 Feb 19 21:09 …
-rw-r–r-- 1 csaba csaba 12 Feb 19 21:19 aFile
-rw-r–r-- 1 csaba csaba 0 Feb 19 21:09 AnotherFile
-rw-r–r-- 1 csaba csaba 0 Feb 24 00:06 ThirdFile

比方说,我们要导航到上级目录,列出它所有的文件,并且使用一个命令将这个列表添加至一个已经存在的文件中。操作符>重定向输出到一个文件并且覆盖该文件;所以我们不能使用它。不过,我们可以使用>>(两个>)来添加新数据到一个已经存在的文件。
csaba@csaba-pc ~/tmp/NetTuts/SecondDir $ cd …
csaba@csaba-pc ~/tmp/NetTuts $ ls -al
total 16
drwxr-xr-x 4 csaba csaba 4096 Feb 19 21:09 .
drwx------ 7 csaba csaba 4096 Feb 19 21:09 …
drwxr-xr-x 2 csaba csaba 4096 Feb 19 21:09 AnotherDir
drwxr-xr-x 2 csaba csaba 4096 Feb 24 00:06 SecondDir
csaba@csaba-pc ~/tmp/NetTuts $ ls -al >> ./SecondDir/ThirdFile

于是我们的文件内容就是这样了:
total 12
drwxr-xr-x 2 csaba csaba 4096 Feb 24 00:06 .
drwxr-xr-x 4 csaba csaba 4096 Feb 19 21:09 …
-rw-r–r-- 1 csaba csaba 12 Feb 19 21:19 aFile
-rw-r–r-- 1 csaba csaba 0 Feb 19 21:09 AnotherFile
-rw-r–r-- 1 csaba csaba 0 Feb 24 00:06 ThirdFile
total 16
drwxr-xr-x 4 csaba csaba 4096 Feb 19 21:09 .
drwx------ 7 csaba csaba 4096 Feb 19 21:09 …
drwxr-xr-x 2 csaba csaba 4096 Feb 19 21:09 AnotherDir
drwxr-xr-x 2 csaba csaba 4096 Feb 24 00:06 SecondDir