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]#
相關文章
相關標籤/搜索