日期:2014-05-16  浏览次数:20701 次

Linux shell : Command 2>&1

之前看到如下shell 命令,一头雾水:


ls temp >list.txt  2>&1
ls temp >/dev/null  2>&1


查阅之后,明白此语句含义,特此记录.


ls temp >list.txt  2>&1     (ps:temp是个不存在的目录)
ls temp >list.txt  :
把标准输出重定向到list.txt文件中,在这里,就是把temp目录下所有的文件,列出来,然后输出到list.txt文件
如果没有这个重定向,那么标准输出默认是控制台
标准输出的句柄应该是1 ,所以,完整的写法应该是:ls temp 1>list.txt 


2>&1  :
在此处 ,表示把标准错误输出写入到list.txt文件
经过这个重定向,标准输出和标准错误输出都重定向到了list.txt中
结果如下:
root:ls temp >list.txt  2>&1 
root:/opt/tmp # more list.txt 
ls: cannot access temp: No such file or directory   //error 信息在文件里


ls temp >/dev/null  2>&1 

这个表示把标准输出,以及标准错误输出都舍弃了,不显示也不保存


如果换一下顺序,如何?
ls temp 2>&1 >list.txt  
标准错误输出定向到控制台,标准内容输出定向到list.txt 
结果如下:
root:/opt/tmp # ls temp 2>&1 >out.txt
ls: cannot access temp: No such file or directory  //error信息直接输出到控制台


总结:
ls temp :表示标准内容输出和标准错误都输出到控制台 
         等同于:ls temp>&1 
ls temp >list :表示标准内容输出到list文件中,标准错误输出还是在控制台
        等同于:ls temp 1>list
ls temp >list   2>&1 :表示标准内容输出到list文件中,标准错误输出也在list文件中 
        等同于:ls temp >list   2>list
                        ls temp 1>list  2>list
                        ls temp 1>list   2>&1

ls temp  2>&  >list :标准错误输出也在控制台,表示标准内容输出到list文件中
        等同于:ls temp  2>&  1>list                     




参考文献:

http://www.cnblogs.com/caolisong/archive/2007/04/25/726896.html
http://www.ningoo.net/html/2007/shell_scripts_stderr_stdout.html

3楼hpf911昨天 22:36
关键是给自己扫盲啊。。。。OSGI restlet 打包酝酿中。。。
2楼exiaoxia昨天 15:51
不错~~ 表达很清楚啊~~ 给我扫盲啦~~~~
1楼zbszhangbosen昨天 14:59
建议你也看看我之前写的这个http://blog.csdn.net/zbszhangbosen/article/details/7434167n明白ncmd 2>&1 > out.txt 与 cmd > out.txt 2>&1的区别