Linux下正常执行的shell脚本,但在crontab下某个命令总是失败

Linux下正常执行的shell脚本,但在crontab下某个命令总是失败。

对,就是这个问题困扰我好久。自己尝试各种打印,在这个命令之前和之后都加了打印,这个命令一执行就像空洞一样,一直没有找到答案。问了几个大牛也没有得到答案。

今天无意间的,搜到这篇文章Use crontab to invoke nohup in script,答案并不明显,也有可能自己灵光一现。试出来的方法,原来是如此的简单。以该篇文章中举例说明。

#!/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 定时任务

*/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这个命令有可能在执行时找不到路径。

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时没必要使用nohup,除非登录退出后在shell和crontab进程间没有了交互,systemd 1号进程将杀死所有进程。

Typically scripts don't run under cron because you've forgotten to set up the environment ($PATH, etc.).

最后这句话,一定可以点醒梦中人。一般脚本在crontab中不能执行的原因是忘记设置环境变量,比如路径不对。

相同的案例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官网介绍,crontab默认路径是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.

参考

Use crontab to invoke nohup in script

ping command excuted in crontab but no output

你可能感兴趣的:(Linux下正常执行的shell脚本,但在crontab下某个命令总是失败)