Linux下正常執(zhí)行的shell腳本骑素,但在crontab下某個(gè)命令總是失敗。
對(duì)刚夺,就是這個(gè)問題困擾我好久献丑。自己嘗試各種打印,在這個(gè)命令之前和之后都加了打印侠姑,這個(gè)命令一執(zhí)行就像空洞一樣创橄,一直沒有找到答案。問了幾個(gè)大牛也沒有得到答案莽红。
今天無意間的妥畏,搜到這篇文章Use crontab to invoke nohup in script,答案并不明顯安吁,也有可能自己靈光一現(xiàn)醉蚁。試出來的方法,原來是如此的簡(jiǎn)單鬼店。以該篇文章中舉例說明网棍。
#!/bin/bash
BASE_PATH=~/scripts
LOG_PATH=${BASE_PATH}/keep_alive.log
write_to_log () {
? ? date >> ${LOG_PATH}
? ? echo ${1} >> ${LOG_PATH}
? ? echo "--------------" >> ${LOG_PATH}
}
pid=$(pgrep long_script)
if [ -z "${pid}" ]; then
? ? write_to_log "long_script is no runnig, starting..."
? ? nohup ${BASE_PATH}/long_script.py &
fi
crontab 定時(shí)任務(wù)
*/30 * * * * /home/scripts/keep_alive.sh
When I run the script manually (in bash,? ./keep-alive.sh) all works well and the long? script starts.
From crontab, the script starts and exits immediately (no issue with the paths/expression), and I see a log written, but the long? script stops. So my conclusion is that? nohup doesn't work the same for crontab? as in bash.
看問題描述 大致遇到了和我一樣的問題。
Can you try seeing the path for nohup from which nohup and use the path directly in? crontab? It is possible that cron might not? know PATH thereby not know where to find nohup 妇智。大致意思是nohup這個(gè)命令有可能在執(zhí)行時(shí)找不到路徑滥玷。
There is no need for nohup when using crontab. Unless your systemd is configured to kill all your processes when you log out there is no interaction between your shell exiting and crontab running processes (or otherwise), and nohup will have no useful effect on that.在使用crontab時(shí)沒必要使用nohup,除非登錄退出后在shell和crontab進(jìn)程間沒有了交互俘陷,systemd 1號(hào)進(jìn)程將殺死所有進(jìn)程罗捎。
Typically scripts don't run under cron because you've forgotten to set up the environment ($PATH, etc.).
最后這句話,一定可以點(diǎn)醒夢(mèng)中人拉盾。一般腳本在crontab中不能執(zhí)行的原因是忘記設(shè)置環(huán)境變量桨菜,比如路徑不對(duì)。
相同的案例ping command excuted in crontab but no output
@reboot ping 1.1.1.1>/home/test.log
After rebooting, the file "test.log" was? generated, however it's only an empty file.? and grep CRON /var/log/syslog shows that the ping command was executed. any one know what the problem is?
I tried some of the solutions that I googled, such as changing ping to /bin/ping or? setting the HOME environment variable, however still not working.
查看crontab官網(wǎng)介紹,crontab默認(rèn)路徑是HOME倒得,如果其它盤符的命令要帶全泻红。
https://www.adminschoice.com/crontab-quick-reference
cron invokes the command from the user’s HOME directory with the shell(/usr/bin/sh).cron supplies a default environment for? every shell, defining:
HOME=user’s-home-directory
LOGNAME=user’s-login-id
PATH=/usr/bin:/usr/sbin:.
SHELL=/usr/bin/sh
Users who desire to have their .profile? executed must explicitly do so in the? crontab entry or in a script called by the? entry.
參考