要在最后一次执行尚未至少在特定时间之前立即中止并退出脚本,可以使用此方法,该方法需要一个存储最后执行日期和时间的外部文件。
将这些行添加到您的Bash脚本的顶部:
#!/bin/bash
# File that stores the last execution date in plain text:
datefile=/path/to/your/datefile
# Minimum delay between two script executions, in seconds.
seconds=$((60*60*24*3))
# Test if datefile exists and compare the difference between the stored date
# and now with the given minimum delay in seconds.
# Exit with error code 1 if the minimum delay is not exceeded yet.
if test -f "$datefile" ; then
if test "$(($(date "+%s")-$(date -f "$datefile" "+%s")))" -lt "$seconds" ; then
echo "This script may not yet be started again."
exit 1
fi
fi
# Store the current date and time in datefile
date -R > "$datefile"
# Insert your normal script here:
不要忘记设置一个有意义的值,datefile=
并seconds=
根据您的需求调整其值($((60*60*24*3))
评估期为3天)。
如果您不想使用单独的文件,也可以将上次执行时间存储在脚本的修改时间戳记中。但是,这意味着对脚本文件进行任何更改都会重置3计数器,并像脚本成功运行一样被对待。
要实现这一点,请将以下代码段添加到脚本文件的顶部:
#!/bin/bash
# Minimum delay between two script executions, in seconds.
seconds=$((60*60*24*3))
# Compare the difference between this script's modification time stamp
# and the current date with the given minimum delay in seconds.
# Exit with error code 1 if the minimum delay is not exceeded yet.
if test "$(($(date "+%s")-$(date -r "$0" "+%s")))" -lt "$seconds" ; then
echo "This script may not yet be started again."
exit 1
fi
# Store the current date as modification time stamp of this script file
touch -m -- "$0"
# Insert your normal script here:
同样,请不要忘记根据seconds=
您的需求调整价值($((60*60*24*3))
评估期为3天)。
*/3
不行?“如果三天还没有过去”:三天后呢?请编辑您的问题并进行澄清。