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.
you can't, but you can use a file to do it
#!/bin/bash
# if we don't have a file, start at zero
if [ ! -f "/tmp/value.dat" ] ; then
value=0
# otherwise read the value from the file
else
value=`cat /tmp/value.dat`
fi
# increment the value
value=$((value + 1))
# show it to the user
echo "value: ${value}"
# and save it for next time
echo "${value}" > /tmp/value.dat
I'm afraid you have to save the state in a file somewhere. The trick is to put it somewhere the user will be able to write to.
yourscriptvar=0
if [ -e "$HOME/.yourscriptvar" ] ; then
yourscriptvar=$(cat "$HOME/.yourscriptvar")
fi
# do something in your script
#save it output the file
echo $yourscriptvar > "$HOME/.yourscriptvar"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With