Linux 里的 2>&1 到底是什么

常常有这样的需求,写一个python文件,以后把这个python作成定时任务形式,按要求定时crontab执行!python

而定时任务常常看到以下格式,譬如我下面这个每三分钟执行一次,并且把python的输出信息每次记录到log日志里面!经常使用的是vim

[root@nessus allpython2019]# crontab -e
*/3 * * * * /usr/bin/python /root/allpython2019/1-FtpSwDownloadcfg20191101.py >> /root/allpython2019/run.log 2>&1
[root@nessus allpython2019]#

那么这个2>&1 到底是什么呢?bash

其实网上不少博文都解释了,以下:ide

run.log 2>&1 含义参考https://blog.csdn.net/liupeifeng3514/article/details/79711694测试

  解答:command > a  2>&1 【command >> a  2>&1】这条命令,能够理解为执行 command 产生的标准输入重定向到文件 a 中,标准错误也重定向到文件 a 中!(a能够是文件run.log或者/dev/null 空设备文件)【若是不这样写 可能只有标准输出打印到log文件去了  而stderr并无被重定向到log中,stderr被打印到了屏幕上】.net

下面是个人测试:日志

(1)测试不加入2>&1 stderr并无被重定向到log中,stderr被打印到了屏幕上blog

(2)测试加入2>&1 stderr也被重定向到log中了crontab

(3)测试经常使用定时crontab执行时候command > a  2>&1 和command >> a  2>&1这2条命令区别,即一个覆盖!一个是追加!我经常使用追加!it

几个基本符号及其含义:

/dev/null 表示空设备文件;
0 表示stdin标准输入;
1 表示stdout标准输出;
2 表示stderr标准错误。

例如我写了下面这个测试程序【这里咱们弄了两条命令,其中t指令并不存在,执行会报错,会输出到stderr。date能正常执行,执行会输出当前时间,会输出到stdout。】
[root@nessus allpython2019]# vim test.sh
#!/bin/sh
t
date
~
~
~
~
"test.sh" [新] 3L, 17C 已写入                                                         
[root@nessus allpython2019]# chmod +x test.sh
[root@nessus allpython2019]# ./test.sh > res1.log
./test.sh:行2: t: 未找到命令              #--------能够看到不加入2>&1 stderr并无被重定向到log中,stderr被打印到了屏幕上
[root@nessus allpython2019]# 
[root@nessus allpython2019]# cat res1.log 
2019年 11月 01日 星期五 10:01:47 CST
[root@nessus allpython2019]# 
[root@nessus allpython2019]# 
[root@nessus allpython2019]# ./test.sh > res2.log 2>&1 #--------能够看到加入2>&1 stderr也被重定向到log中了
[root@nessus allpython2019]# 
[root@nessus allpython2019]# 
[root@nessus allpython2019]# cat res2.log 
./test.sh:行2: t: 未找到命令
2019年 11月 01日 星期五 10:03:08 CST
[root@nessus allpython2019]# 
[root@nessus allpython2019]# 
[root@nessus allpython2019]# ./test.sh > res2.log 2>&1  #---------------下面演示咱们经常使用的>和>>区别,就是一个覆盖!一个是追加!
[root@nessus allpython2019]# cat res2.log 
./test.sh:行2: t: 未找到命令
2019年 11月 01日 星期五 10:03:24 CST
[root@nessus allpython2019]# 
[root@nessus allpython2019]# 
[root@nessus allpython2019]# ./test.sh >> res2.log 2>&1
[root@nessus allpython2019]# cat res2.log 
./test.sh:行2: t: 未找到命令
2019年 11月 01日 星期五 10:03:24 CST
./test.sh:行2: t: 未找到命令
2019年 11月 01日 星期五 10:03:40 CST
[root@nessus allpython2019]# ./test.sh >> res2.log 2>&1
[root@nessus allpython2019]# cat res2.log 
./test.sh:行2: t: 未找到命令
2019年 11月 01日 星期五 10:03:24 CST
./test.sh:行2: t: 未找到命令
2019年 11月 01日 星期五 10:03:40 CST
./test.sh:行2: t: 未找到命令
2019年 11月 01日 星期五 10:03:44 CST
[root@nessus allpython2019]# 
[root@nessus allpython2019]# 
[root@nessus allpython2019]#
相关文章
相关标签/搜索