Chinaunix首页 | 论坛 | 博客
  • 博客访问: 187325
  • 博文数量: 20
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 965
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-18 23:28
文章分类

全部博文(20)

文章存档

2015年(1)

2014年(19)

分类: LINUX

2014-07-04 12:00:33


首先要认识到:

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

0: Standard Input (STDIN) 
1: Standard Output (STDOUT) 
2: Standard Error Output (STDERR) 

在标准情况下, 这些FD分别跟如下设备关联: 
stdin(0): keyboard  键盘输入,并返回在前端 
stdout(1): monitor  正确返回值 输出到前端 
stderr(2): monitor 错误返回值 输出到前端 

然后来解释dev/null 2>&1、2>1以及2>&1 之间的区别:

1. 标准输入stdin文件描述符为0,标准输出stdout文件描述符为1,标准错误stderr文件描述符为2

2. /dev/null 空设备,相当于垃圾桶

3. 重定向符号:>

3. 2>1 与 2>&1 的区别
   2>1, 把标准错误stderr重定向到文件1中
   2>&1,把标准错误stderr重定向到标准输出stdout

4. 举例:
   假设有脚本test.sh,内容如下,t是一个不存在的命令,执行脚本进行下面测试。
   # cat test.sh
     t
     date

   标准输出重定向到log,错误信息输出到终端上,如下:
   # ./test.sh > log
     ./test.sh: line 1: t: command not found
   # cat log
     Thu Oct 23 22:53:02 CST 2008 
   删除log文件,重新执行,这次是把标准输出定向到log,错误信息定向到文件1
   # ./test.sh > log 2>1
   #
   # cat log
   Thu Oct 23 22:56:20 CST 2008
   # cat 1
   ./test.sh: line 1: t: command not found
   #

   把标准输出重定向到log文件,把标准错误重定向到标准输出
   # ./test.sh > log 2>&1
   #
   # cat log
   ./test.sh: line 1: t: command not found
   Thu Oct 23 22:58:54 CST 2008
   #

   把错误信息重定向到空设备
   # ./test.sh 2>/dev/null
   Thu Oct 23 23:01:07 CST 2008
   #  
   把标准输出重定向到空设备
   # ./test.sh >/dev/null
     ./test.sh: line 1: t: command not found

   把标准输出和标准错误全重定向到空设备
   #./test.sh >/dev/null 2>&1
   #


   把标准输出和标准错误全重定向到空设备
   #./test.sh >/dev/null 2>&1

阅读(1612) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~