I’m trying to check if a number differs from what it was last time it was checked, in this case checking a number every minute, using Linux scripts and cron.
eg:
newNum = getNum() if oldNum != newNum: run some code oldNum = newNum (repeat every minute using crontab)
But the problem I am having is that the variables aren’t accessible between scripts and using source (eg. source script.sh) runs the script again, hence getting the latest version, not the one from a minute ago.
The best I’ve got is running a first script which gets the current number, then sleeps for a minute, then runs a second script which is essentially the first two lines of the code above.
eg:
oldNum = getNum() sleep 60 export oldNum script2.sh
This seems inefficient to me and I’d like to know if there is a better solution if possible.
Advertisement
Answer
You could cache the previous number in a file:
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 "%dn" "$newNum" > "$number_cache"