5

I need to do something like this

  • Set a unix variable with a default value.
  • Run a shell script which reads that variable and process it.
  • Upon processing it may or may not change the value of that variable.

Run this script every hour and ensure that the value of this variable now is the value set by last run of this script.

I am mostly looking for how to setting and retaining value. I did the following and it didn't work.

export last_build="hello"
source .bashrc

Then in my script which processes this variable

echo $last_build     
export last_build="hello again"
echo $last_build

When I run this script, I get something like

hello    
hello again

When I run second time, I am expecting the output to be

hello again
hello again

but it sill gives same output as the first run.

4
  • Write them to and read them from a file Commented Nov 7, 2014 at 23:40
  • The 'every hour' bit is puzzling (or is going to be the hard part). Are you thinking of running the script from cron, or is it supposed to be run in your current interactive (login) shell? You can store variable settings in a file and use the dot . (or source) command to read that file. And you can run some other script that modifies what's in the file. You could have a cron job that is run every hour that updates the file. And every time you run a program (script) that needs the environment variable, you could have the script read that file. Commented Nov 7, 2014 at 23:41
  • The envdir approach is a good one -- have a dedicated directory, one file per variable. Easy to populate your environment from such a directory (for f in *; do printf -v "$f" %s "$(<"$f")"; done), easy to modify, easy to save. Commented Nov 7, 2014 at 23:43
  • export only exports to your own subprocesses. The namespace is not more global, or more persistent, than that. Commented Nov 7, 2014 at 23:46

1 Answer 1

9

Shell variables are stored per-process, since each shell script is its own process, you cannot persist variables across processes this way. There are various ways to communicate between processes, though:

  1. Pipes
  2. Shared Memory
  3. Message Queue
  4. Semaphores
  5. Files

For your purposes, it would seem that files are the easiest approach. Using bash, to write to the file:

echo $VAR > /tmp/process.tmp.file.txt

and read from it:

export VAR=`cat /tmp/process.tmp.file.txt`
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.