3

I have a bash script which is run every 10m by cron. The script performs an expensive calculation for some value (say variable x=value). I need to "cache" this value for 2-3 hours. What are possible solutions to this problem?

I tried memcached but it doesn't seem to play well with bash.

9

Write a second script that does the actual calculation and saves the result to a file:

# calculate $curval
echo $curval > /var/foo/value.txt

Schedule it with cron to run every 2-3 hours.

In the "every 10 minutes" script, simply read the current value from the file:

curval=`cat /var/foo/value.txt`

A nice refinement is to call the calculation script from the "every 10 minutes" script if the value.txt file doesn't exist yet. You could even make it add the crontab entry if it's missing.

  • 4
    Three issues: You should quote $curval to avoid issues with IFS, and you should also use printf, as you can't tell what's in the file, so echo is unsafe (it could pass any argument to echo). Also, there's no need to invoke the external command cat to read a file into a variable when bash can do it itself, in the form $(</var/foo/value.txt). – Chris Down Sep 21 '11 at 14:17
  • Yes, all that. :) – Warren Young Sep 21 '11 at 14:32
1

I'd agree with writing the result to a file, set the variable in the file

curval=the_value

Then in the shell (or another script)

source current_variable_value_result_file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.