Welcome 微信登录

首页 / 操作系统 / Linux / Linux shell : Command 2>&1

之前看到如下Linux hell 命令,一头雾水: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        MySQL主从架构及基于SSL实现数据复制sed处理变量替换相关资讯      Linux Shell 
  • Linux基础知识:shell基础命令  (今 10:39)
  • Linux系统监控shell脚本  (04月09日)
  • Linux shell脚本编程  (03月01日)
  • Linux shell数组  (07月26日)
  • Linux Shell实现批量关闭局域网中  (03月10日)
  • Linux系统入门教程:如何知道当前  (11/27/2015 08:36:09)
本文评论 查看全部评论 (0)
表情: 姓名: 字数