【linux编程】文本处理-重定向

2017-12-26  本文已影响0人  leadingsci
重定向

重定向 1>&2 2>&1的定义

在 shell 程式中,最常使用的 FD (file descriptor) 大概有三个, 分别是:

在标准情况下, 这些FD分别跟如下设备关联:

举例

当前目录只有一个文件 a.txt.

[root@redhat box]# ls 

a.txt 

[root@redhat box]# ls a.txt b.txt          

错误返回值

ls: b.txt: No such file or directory

由于没有b.txt这个文件, 于是返回错误值, 这就是所谓的2输出

正确返回值

a.txt 而这个就是所谓的1输出

再接着看:

[root@redhat box]# ls a.txt b.txt  1>file.out 2>file.err 

执行后,没有任何返回值. 原因是, 返回值都重定向到相应的文件中了,而不再前端显示

[root@redhat box]# cat file.out 

a.txt 

[root@redhat box]# cat file.err 

ls: b.txt: No such file or directory 

一般来说,"1>" 通常可以省略成 ">".

即可以把如上命令写成: ls a.txt b.txt >file.out 2>file.err


"1>&2" 和 "2>&1"的区别

举个例子.

[root@redhat box]# ls a.txt b.txt 1>file.out 2>&1 

[root@redhat box]# cat file.out 

ls: b.txt: No such file or directory 

a.txt 

现在, 正确的输出和错误的输出都定向到了file.out这个文件中, 而不显示在前端.

补充下, 输出不只1和2, 还有其他的类型, 这两种只是最常用和最基本的.

上一篇下一篇

猜你喜欢

热点阅读