0

I have a script running a get command and store the output in a variable called newvalue and one more variable called oldvalue (manually stored some value in it). Then script subtract newvalue - oldvalue and store the result in a variable called finalvalue and echo's final value. I have to run this script using cron job every 4 hour and send email containing echo of finalvalue. Till here everything is working fine. Now i want this script to update the oldvalue variable with value of newvalue once its done sending the email. Means every 4 hour when script run, it should change the value of variable oldvalue with last newvalue. Please suggest the workaround.

1
  • Show the scripts, what do you expect as result and so on. Mar 16 '20 at 11:04
4

When you run a script, no matter if you run it from cron or directly in the command line, that script runs in its own "subshell", in its own environment. Any variables set during the script's execution are only visible to that script while it runs. If you then run the same script again, it is completely independent of the first run and there is no way for a variable from the first execution to somehow survive and be picked up by the second, separate execution.

Therefore, if you need to keep a value across different instances of the script, you are going to have to use a temporary file to store it. Just add something like this to your script:

oldValue=$(cat /path/to/temp/file);
newValue=$(whatever gives you the new value)
finalValue=$((newvalue - oldvalue))
echo "$finalValue" > /path/to/temp/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.