按计划运行 bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41952209/
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-18 15:41:06  来源:igfitidea点击:

Run bash script on schedule

bashtimebackup

提问by Sebastian Bia?ek

I have some problem with bash script. I need to add some content to it. My script need to run at a certain time but I don't know how to do that. It should work like this: I have a variable then I assign a time like 3200s. When I run the program, then the script will create backups every 3200s but only if some files changed. What am I doing wrong?

我对 bash 脚本有一些问题。我需要添加一些内容。我的脚本需要在某个时间运行,但我不知道该怎么做。它应该是这样工作的:我有一个变量,然后我分配一个像 3200s 这样的时间。当我运行程序时,脚本将每 3200 秒创建一次备份,但前提是某些文件发生更改。我究竟做错了什么?

!/bin/bash

SOURCE="/var/www/my_web/load/"
BACKUP="/home/your_user/load/"
LBACKUP="/home/your_user/load/latest-full/"

DATE=$(date +%Y-%m-%d-%T)

DESTINATION="$BACKUP"/"$DATE"-diff/

rsync -av --compare-dest="$LBACKUP" "$SOURCE" "$DESTINATION"

cd "$DESTINATION"
find . -depth -type d -empty -delete

采纳答案by webb

here i have added that feature to your script:

在这里,我已将该功能添加到您的脚本中:

usage:

用法:

./yourscript.sh 3200

script:

脚本:

#!/bin/bash

# make sure you gave a number of seconds:
[ 0 -gt 0 ] || exit

while true; do
    SOURCE="/var/www/my_web/load/"
    BACKUP="/home/your_user/load/"
    LBACKUP="/home/your_user/load/latest-full/"

    DATE=$(date +%Y-%m-%d-%T)

    DESTINATION="$BACKUP"/"$DATE"-diff/

    rsync -av --compare-dest="$LBACKUP" "$SOURCE" "$DESTINATION"

    cd "$DESTINATION"
    find . -depth -type d -empty -delete

    sleep 
done

if you get an error like bash: ./yourscript.sh: Permission denied, then you need to do this once: chmod +x yourscript.shto make the script executable.

如果您收到类似 的错误bash: ./yourscript.sh: Permission denied,那么您需要执行一次:chmod +x yourscript.sh使脚本可执行。

to continue running in background even after you leave the terminal window:

即使在您离开终端窗口后继续在后台运行:

nohup ./yourscript.sh 3200 &

to run in background on schedule even after restart:

即使在重新启动后也按计划在后台运行:

use cron, e.g., Using crontab to execute script every minute and another every 24 hours

使用cron,例如,使用 crontab 每分钟执行一次脚本,每 24 小时执行一次