温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Linux 里的 2>&1 究竟是什么

发布时间:2020-05-12 03:21:53 来源:网络 阅读:483 作者:老肖的博客 栏目:系统运维

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

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

[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 究竟是什么呢?

其实网上很多博文都解释了,如下:

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被打印到了屏幕上】

下面是我的测试:

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

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

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

几个基本符号及其含义:

/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]#


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI