bash 帮助调试具有正确脚本路径并在手动触发时工作的 cron 作业

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3611812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:33:07  来源:igfitidea点击:

Help debugging a cron job which has the correct script path and works when manually triggered

linuxbashcronunrar

提问by kenny99

I'm struggling trying to debug a cron job which isn't working correctly. The cron job calls a shell script which should unrar a rar file - this works correctly when i run the script manually, but for some reason it's not working via cron. I am using the absolute file path and have verified that the path is correct. Has anyone got any ideas why this could be happening?

我正在努力调试无法正常工作的 cron 作业。cron 作业调用一个 shell 脚本,该脚本应该解压缩一个 rar 文件 - 当我手动运行脚本时,这可以正常工作,但由于某种原因,它无法通过 cron 工作。我正在使用绝对文件路径并已验证路径是否正确。有没有人知道为什么会发生这种情况?

回答by DarkDust

Well, you already said that you have used absolute paths, so the number 1 problem is dealed with.

好吧,您已经说过您使用了绝对路径,因此解决了第一个问题。

Next to check are permissions. As which user is the cron job run ? Does he have all the permissions necessary ?

接下来要检查的是权限。cron 作业以哪个用户身份运行?他是否拥有所有必要的权限?

Then, a little trick: if you have a shell script that fails and it's not run in a terminal I like to redirect the output of it to some files. Right at the start of the script, add:

然后,一个小技巧:如果你有一个失败的 shell 脚本并且它没有在终端中运行,我喜欢将它的输出重定向到一些文件。在脚本的开头,添加:

exec &>/tmp/my.log

This will redirect STDOUT and STDERR to /tmp/my.log. Then it might also be a good idea to also add the line:

这会将 STDOUT 和 STDERR 重定向到/tmp/my.log. 那么添加以下行也可能是一个好主意:

set -x

This will make bash print which command it's about to execute, and at what nesting level.

这将使 bash 打印它将要执行的命令以及嵌套级别。

Happy debugging !

调试愉快!

回答by ennuikiller

The first thing to check when cron jobs fail is to see if the full environment is available to the script you are trying to execute. In other words, you need to realize that a job executed via cron runs as a detached process meaning it is not associated with a login environment. Therefore whenever you try to debug a cron job that works when you execute manually, you need to be sure the same environment is available to the cronjob as is available to you when you execute it manually. This include any PATH settings, and other envvars that the script may depend on.

当 cron 作业失败时要检查的第一件事是查看您尝试执行的脚本是否可以使用完整的环境。换句话说,您需要意识到通过 cron 执行的作业作为分离的进程运行,这意味着它与登录环境无关。因此,每当您尝试调试手动执行时有效的 cron 作业时,您需要确保 cronjob 可用的环境与手动执行时可用的环境相同。这包括任何 PATH 设置,以及脚本可能依赖的其他环境变量。

回答by Vanuan

For me, the problem was a different shell interpreter in crontab.

对我来说,问题是 crontab 中的不同 shell 解释器。