使用 cron 运行脚本的正确方法?
使用 cron 运行脚本时,内部调用的任何可执行文件都必须具有完整路径。 我发现这个试图运行 wondershaper ,当它尝试调用 tc 时显示许多错误。 所以我的问题是,克服这个问题的正确方法是什么?
可能的解决方案:
- cd 到可执行文件夹并准备指向任何其他称为可执行文件的符号链接(不确定它是否有效 - 低可移植性)
- 在脚本中使用完整路径(它有效 - 跨不同发行版的低可移植性)
- 导出路径变量脚本内需要的路径(不确定它是否有效)
好吧,提前感谢任何人的帮助。
When running a script with cron, any executable called inside must have the full path. I discovered this trying to run wondershaper, when many errors showed when it tried to call tc. So my question is, what's the proper way to overcome this problem?
Possible solutions:
- cd to the executable folder and prepare symbolic links to any other called executable there (not sure if it works - low portability)
- use full paths in the script (it works - low portability across different distros)
- exporting a path variable with the needed paths inside the script (not sure if it works)
Well, thanks in advance for anyone helping.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 linux/bsd/mac,您可以在
crontab
中设置一些环境变量,例如PATH
,这样您就可以开始了。如果你在Solaris上,那么,我为你祈祷。 但是,我也有一个答案:我通常在运行任何内容之前获取
.profile
:请注意,我的
.profile
加载.bash_profile
和 <代码>.bashrc。 只要确保您获取的任何文件都有您需要的内容即可。If you're on linux/bsd/mac you can set some environment variables like
PATH
right in thecrontab
, and with that you're generally good to go.If you're on Solaris, well, I pray for you. But, I do have an answer too: I generally source
.profile
before running anything:Mind you, my
.profile
loads.bash_profile
and.bashrc
. Just be sure whatever file you source has what you need.在 cron 作业中声明变量更加明确且更易于维护:您需要修改的所有内容都包含在 cron 作业中,并且如果将其移动到另一个系统,则不需要传输多个文件。
Declaring variables inside your cron job is more explicit and easier to maintain : all you have to modify is contained in your cron job, and you don't need to transfer multiple files should you move it to another system.
由于 cron 不运行登录,因此不会获取 .profile 和 /etc/profile。 因此 PATH 可能未设置为您期望的值。 我可以
您的符号链接技巧假设。 在 PATH 中,但看起来不太好
Since cron does not run login, .profile and /etc/profile are not sourced. Therefore PATH may not be set to a value you expect. I would either
Your trick with symlinks assumes . is in the PATH and just does not seem nice
我的建议:
在外部文件中设置所有变量。 我使用位于 /etc/process_name 或类似文件中的“process_name.env”文件。 假设您有一个备份脚本。 然后您:
修改您的备份脚本并在 Shebang 之后添加此行:
。 /etc/backup.env #备份环境的完整路径之前有一个点和一个空格。
IMO 这种方法比在 CRON 定义中声明变量更好,因为:
问候
My recomendation:
Set all variables in a external file. I use 'process_name.env' file located in /etc/process_name or similar. Imagine you have a backup script. Then you:
Modify your backup script and add this line after Shebang:
. /etc/backup.env #There is a dot and a space before full path to backup environment.
IMO this approach is better than declaring variables at CRON definitions because:
Regards