应用背景
如下例所示,aa是不识别的命令。
在执行./test.sh时,输出两行,第一行表示错误输出;第二行表示标准输出。
如果把脚本test.sh执行的所有信息,写入脚本日志test.log,那么就出现了人为偏差,脚本日志不包含错误输出的内容;这样不方便脚本执行的debug日志需求。
[qilei@localhost ~]$ cat ./test.sh
#!/bin/bash
aa
date
[qilei@localhost ~]$ ./test.sh
./test.sh: line 2: aa: command not found
Mon Mar 6 05:54:00 PST 2017
[qilei@localhost ~]$ ./test.sh > test.log
./test.sh: line 2: aa: command not found
[qilei@localhost ~]$ cat test.log
Mon Mar 6 05:54:10 PST 2017
/dev/null 1 & 2的介绍
/dev/null :代表空设备文件
> :代表重定向到哪里,例如:echo "123" > /home/123.txt
1 :表示stdout标准输出,系统默认值是1,所以">/dev/null"等同于"1>/dev/null"
2 :表示stderr标准错误
& :表示等同于的意思,2>&1,表示2的输出重定向等同于1
把错误输出和标准输出,都导入日志test.log里
- 把错误输出和标准输出,都导入日志test.log里;利用的是
2>&1
。
-
2>&1
,意思是错误输出等同于标准输出。所以使得./test.sh > test.log
,可以把标准输出和错误输出全部导入日志test.log里。
- 注意:
2>&1
,中间不能有空格。
- 注意:
2>&1
,必须写在最后,否则会失去原有意义。
-
tee
命令,不能替代>重定向
命令
[qilei@localhost ~]$ ./test.sh > test.log 2>&1
[qilei@localhost ~]$ cat test.log
./test.sh: line 2: aa: command not found
Mon Mar 6 06:00:29 PST 2017
[qilei@localhost ~]$ ./test.sh | tee test.log 2>&1
./test.sh: line 2: aa: command not found
Mon Mar 6 06:00:41 PST 2017
[qilei@localhost ~]$ cat test.log
Mon Mar 6 06:00:41 PST 2017
屏蔽标准输出和错误输出信息
如下例所示,
1. /dev/null
是空文件,就是为了屏蔽输出而已。
2. > /dev/null
,默认是把标准输出屏蔽,但不能屏蔽错误输出。等同于 1 > /dev/null
3. 2 > /dev/null
,默认是把错误输出屏蔽,但不能屏蔽标准输出。
4. 2 > /dev/null
,2和>之间可以有空格。与2&>1有些不同。具体原因先不管了。
[qilei@localhost ~]$ ./test.sh > /dev/null
./test.sh: line 2: aa: command not found
[qilei@localhost ~]$ ./test.sh > /dev/null 2>&1
[qilei@localhost ~]$ ./test.sh 2> /dev/null
Mon Mar 6 06:04:56 PST 2017
[qilei@localhost ~]$ ./test.sh 1> /dev/null
./test.sh: line 2: aa: command not found
[qilei@localhost ~]$ ./test.sh 1 > /dev/null
./test.sh: line 2: aa: command not found
[qilei@localhost ~]$ ./test.sh 2 > /dev/null
./test.sh: line 2: aa: command not found
[qilei@localhost ~]$
tee命令,如何把标准输出和错误输出都导入test.log里
tee命令,如何把标准输出和错误输出都导入test.log里?下例解决。
1. 注意,2>&1
要放在tee
命令之前。
[qilei@localhost ~]$ ./test.sh | tee test.log 2>&1
./test.sh: line 2: aa: command not found
Mon Mar 6 06:17:27 PST 2017
[qilei@localhost ~]$ cat test.log
Mon Mar 6 06:17:27 PST 2017
[qilei@localhost ~]$ ./test.sh 2>&1 | tee test.log
./test.sh: line 2: aa: command not found
Mon Mar 6 06:17:48 PST 2017
[qilei@localhost ~]$ cat test.log
./test.sh: line 2: aa: command not found
Mon Mar 6 06:17:48 PST 2017
[qilei@localhost ~]$