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

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"

Leave a Comment