使用 Linux 脚本和 Cron 定期比较变量

Compare A Variable Regularaly Using Linux Scripts and Cron

我正在尝试检查一个数字是否与上次检查的数字不同,在本例中使用 Linux 脚本和 cron 每分钟检查一个数字。

例如:

newNum = getNum()

if oldNum != newNum: run some code

oldNum = newNum

(repeat every minute using crontab)

但我遇到的问题是变量无法在脚本之间访问,并且使用源代码(例如源代码 script.sh)再次运行脚本,因此获得最新版本,而不是来自分钟前。

我得到的最好的是 运行 第一个脚本获取当前数字,然后休眠一分钟,然后运行第二个脚本,它基本上是上面代码的前两行。

例如:

oldNum = getNum()

sleep 60

export oldNum

script2.sh 

这对我来说似乎效率低下,我想知道是否有更好的解决方案。

您可以在文件中缓存之前的数字:

number_cache=/path/to/cache_file

# read the previous number
oldNum=$(< "$number_cache" )
# acquire the new number
newNum=$(getNum)

if [[ "$oldNum" -eq "$newNum" ]]; then
    do_something
fi

# cache the new number
printf "%d\n" "$newNum" > "$number_cache"