Linux Crontab未启动脚本

Linux Crontab未启动脚本,linux,ubuntu,cron,ubuntu-18.04,Linux,Ubuntu,Cron,Ubuntu 18.04,我尝试每天12点通过crontab运行以下脚本: #!/bin/sh mount -t nfs 10.1.25.7:gadal /mnt/NAS_DFG echo >> ~/Documents/Crontab_logs/logs.txt date >> ~/Documents/Crontab_logs/logs.txt rsync -ar /home /mnt/NAS_DFG/ >> ~/Documents/Crontab_logs/logs.txt 2>

我尝试每天12点通过crontab运行以下脚本:

#!/bin/sh
mount -t nfs 10.1.25.7:gadal /mnt/NAS_DFG
echo >> ~/Documents/Crontab_logs/logs.txt
date >> ~/Documents/Crontab_logs/logs.txt
rsync -ar /home /mnt/NAS_DFG/ >> ~/Documents/Crontab_logs/logs.txt 2>&1
unmout /mnt/NAS_DFG
由于它需要在sudo中运行,因此我在“sudo crontab”中添加了以下行:

someone@something:~$ sudo crontab -l
# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command

0 12 * * * ~/Documents/Crontab_logs/Making_save.sh 
但它没有运行。我提到,仅执行脚本thourgh:

sudo ~/Documents/Crontab_logs/Making_save.sh
工作正常,只是日志文件中没有写入rsync命令的输出

你知道怎么回事吗?我想我检查了错误的主要来源,即使用shell,在末尾留下空行等…

sudo crontab创建了一个作业,如果您能够正确配置它,它将在root的crontab中运行;根crontab中的语法不同。当cron运行作业时,$HOME和~如果您使用带有tilde扩展的shell或脚本语言,则将引用root等的HOME

你也许应该简单地加上

0 12 * * * sudo ./Documents/Crontab_logs/Making_save.sh
改为您自己的crontab

请注意,crontab根本没有tilde扩展,但我们可以依赖这样一个事实:cron将始终运行在您的主目录之外


。。。尽管这仍然会有问题,因为如果脚本在sudo下运行并创建新文件,这些文件将归root所有,并且不能由常规用户帐户更改。更好的解决方案仍然是只使用sudo运行实际的mount和umount命令,并尽量减少在特权帐户上运行的代码量,也就是说,从crontab中删除sudo,而是将它添加到脚本中需要它的各个命令中。

将此标记为迁移到该命令~从cron运行时可能不起作用。将其更改为绝对路径。如果您致力于不指定完整路径,那么使用$HOME变量来代替~,可能会得逞。要知道$HOME可能是root的家,而不是你的家,而且你的脚本可能仍然找不到。这有一个可疑的荣誉,那就是几乎所有你可能遇到的问题。值得一提的是,有一个相当详尽的故障排除提示列表。感谢您的详细回答。因此,如果我将sudo放入crontab或mount and umount命令,我需要将密码传递给cron?最简单但安全的方法是什么?如果您有权限,请在sudo配置中将NOPASSWD:添加到这些命令中。如果没有,限制特权的一种方法是重构脚本以要求root运行,但对于非特权部分,请转到您在su或sudo的个人帐户。我不知道我们可以为sudo添加此类例外。谢谢!