經常有這樣的需求,寫一個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]#