首页 文章

如何从Bash打开crontab并向cron添加注释?

提问于
浏览
0

目前这是我们的方案 .

  • SSH进入节点1

  • sudo crontab -e

  • 将此 * * * * * /rsync.sh >>/dev/null 2>&1 更改为 #* * * * * /rsync.sh >>/dev/null 2>&1

  • cd /var/www/www.site.com/public_html/

  • npm run prod

  • 等待npm成功

  • sudo crontab -e

  • 将此 #* * * * * /rsync.sh >>/dev/null 2>&1 更改为 * * * * * /rsync.sh >>/dev/null 2>&1

  • 退出SSH

因此,每次我们部署时,我们都会在crontab中添加或删除注释,然后添加或删除 # . 这很耗时,所以我写了这个脚本 .

我只有一条线 .

(我不是bash专家)

#!/bin/bash

START_TIME=`date +%s`

# turn off rsync by deleting cron (from root user)
crontab -e -u root

# deploy to production node 1
npm run prod
sudo service varnish restart
END_TIME=`date +%s`

# turn on rsync by making the cron again
crontab -e -u root | { cat; echo "* * * * * /root/scripts/sync.sh >>/dev/null 2>&1"; } | crontab -

echo -e ""

这不起作用,因为它不是添加一行,也不是我想要的查找和删除代码 . 有人帮吗?

我收到此错误:

no crontab for root - using an empty one Vim: Warning: Output is not to a terminal 它挂起..

2 回答

  • 2

    按照@Jeff Richards的建议使用 /etc/cron.d .

    /etc/cron.d 中的文件不需要使用 crontab 命令进行更新 .

    #!/bin/bash
    
    set -uex
    
    START_TIME=$(date +%s)
    
    # turn off rsync by deleting cron
    sudo rm /etc/cron.d/www.site.com_sync
    
    # deploy to production node 1
    cd /var/www/www.site.com/public_html/
    npm run prod
    service varnish restart
    
    END_TIME=$(date +%s)
    
    # turn on rsync by making the cron again
    echo '* * * * *  root  /root/scripts/sync.sh >>/dev/null 2>&1' | sudo tee /etc/cron.d/www.site.com_sync
    
  • 0

    这是我为未来人们使用的解决方案

    #!/bin/bash
    ## DELETE THE RYSYNC COMMAND
    sudo crontab -r -u root
    ( cd app/src ; gulp static-builder )
    npm run prod
    ## RESTART VARNISH
    sudo service varnish restart
    ## START THE RYSYNC COMMAND
    (sudo crontab -u root -l; echo "* * * * * /root/scripts/sync.sh >>/dev/null 2>&1") | sudo crontab -u root -
    

    与其他人的命令建议相比,我不推荐它;但是现在,我们将使用它 .

    我完全删除了该用户的cron . 然后我在部署到 生产环境 后再次写入该行 .

相关问题