Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 8 down vote accepted

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.

share|improve this answer
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

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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