Search code examples
linuxbashvariables

Variable in Bash Script that keeps it value from the last time running


Can I create a Bash script with persistent variable-values?

For example, I initialize a variable with 0 when the script runs for the first time (during a specific time limit), and the variable increases automatically with every time the script is running.


Solution

  • You can't, but you can use a file to do it

    #!/bin/bash
    
    valuefile="/tmp/value.dat"
    
    # if we don't have a file, start at zero
    if [ ! -f "$valuefile" ]; then
        value=0
    
    # otherwise read the value from the file
    else
        value=$(cat "$valuefile")
    fi
    
    # increment the value
    value=$((value + 1))
    
    # show it to the user
    echo "value: ${value}"
    
    # and save it for next time
    echo "${value}" > "$valuefile"