【问题标题】:Script works fine standalone, but is incomplete as cron脚本独立工作正常,但作为 cron 不完整
【发布时间】:2021-05-17 07:07:19
【问题描述】:

我有这个备份脚本,我试图将它作为 cron 作业在一夜之间运行。 它可以作为独立脚本正常工作。备份每个文件夹。我将它设置为 root (sudo crontab -e)。但作为一项 cron 作业,它只备份第一个文件夹(“/home”),而不备份其他文件夹。 对可能发生的事情有任何想法吗? 另外,我也会对我的整体方法提出任何建议。


outputFile="/mnt/synology/"$now"_backup.tar.gz"

inputFiles="/home"
inputFiles+=" /var/www"  #webpages for apache
inputFiles+=" /etc/fstab" #needed to mount synology share drive on /mnt
inputFiles+=" /etc/NetworkManager/NetworkManager.conf"  #to keep resolvd dead, so it doesn't interfere with ubound
inputFiles+=" /etc/ufw/*.*"  #to get all the firewall rules setup under ufw
inputFiles+=" /etc/apache2/sites-available/*.*" #apache websites available
inputFiles+=" /etc/mysql/mysql.conf.d/*.cnf"  #to allow nonlocal access into mysql server. It allows from everywhere. Y>inputFiles+=" /etc/samba/*.conf"  #samba config
inputFiles+=" /etc/unbound/*.conf"  #unbound configuration files
inputFiles+=" /var/spool/cron"  #crontab config files

sudo tar czf $outputFile --exclude=".*" $inputFiles

【问题讨论】:

  • 通过在 chron 条目中添加类似 >/tmp/cronjob.log 2>&1 的内容来捕获其输出和错误消息。另外,它有适当的shebang吗?如果不是,可能是running under a shell that doesn't support +=
  • 对于将来看到这个的人来说,听起来 ubuntu 下 cron 的默认值是 sh 而我的脚本是 bash。在我的脚本顶部添加 #!/bin/bash 可以解决问题。

标签: bash ubuntu cron


【解决方案1】:

问题原来是脚本中缺少 shebang 行。第一行应该是这样的:

#!/bin/bash

...告诉系统使用 bash 运行脚本,而不是使用它的默认 shell。哪个 shell 被用作默认值很难预测,因此最好明确指定它,尤其是,如果您使用基本 shell 语法的任何 bash 扩展(如 +=)。如果您不知道什么是 bash 扩展,请使用 bash shebang 以防万一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    相关资源
    最近更新 更多