Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 205
Lokomotywa Avatar asked Mar 28 '12 09:03

Lokomotywa


2 Answers

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
like image 169
dldnh Avatar answered Oct 04 '22 00:10

dldnh


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"
like image 31
Gareth Davis Avatar answered Oct 04 '22 00:10

Gareth Davis