1

I need to increment a number inside a varaible in a bash script. But after the script is done, the variable should be exported with the new number and available next time the script is running.

IN MY SHELL

    set x=0

SCRIPT

" If something is true.. do"
export x=$(($x+1)) //increment variable and save it for next time
if [ $x -eq 3 ];then 
    echo test
fi
exit
1
  • 1
    Persistent variables are called files. Save the state in a file and read it back. E.g. to save use echo "$x" > myfile and to load use x=$(cat myfile) Commented Jan 20, 2017 at 13:34

2 Answers 2

3

You cannot persist a variable in memory between two processes; the value needs to be stored somewhere and read on the next startup. The simplest way to do this is with a file. (The fish shell, which supports "universal" variables, uses a separate process that always runs to communicate with new shells as they start and exit. But even this "master" process needs to use a file to save the values when it exits.)

# Ensure that the value of x is written to the file
# no matter *how* the script exits (short of kill -9, anyway)
x_file=/some/special/file/somewhere
trap 'printf '%s\n' "$x" > "$x_file"' EXIT

x=$(cat "$x_file")   # bash can read the whole file with x=$(< "$x_file")
# For a simple number, you only need to run one line
# read x < "$x_file"
x=$((x+1))
if [ "$x" -eq 3 ]; then
   echo test
fi
exit
Sign up to request clarification or add additional context in comments.

Comments

0

Exporting a variable is one way only. The exported variable will have the correct value for all child processes of your shell, but when the child exits, the changed value is lost for the parent process. Actually, the parent process will only see the initial value of the variable.

Which is a good thing. Because all child processes can potentially change the value of an exported variable, potentially messing things up for the other child processes (if changing the value would be bi-directional).

You could do one of two things:

  • Have the script save the value to a file before exiting, and reading it from the file when starting
  • Use source your-script.bash or . your-script.bash. This way, your shell will not create a child process, and the variable gets changed in same process

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.