Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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
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


Then in the shell (or another script)

source current_variable_value_result_file
share|improve this answer

Your Answer


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.