Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: increment a variable from a script every time when I run that script

I want that a variable from a script to be incremented every time when I run that script. Something like this:

#!/bin/bash    
n=0   #the variable that I want to be incremented
next_n=$[$n+1]
sed -i "2s/.*/n=$next_n/" ${0}
echo $n

will do the job, but is not so good if I will add other lines to the script before the line in which the variable is set and I forget to update the line sed -i "2s/.*/n=$next_n/" ${0}.

Also I prefer to not use another file in which to keep the variable value.

Some other idea?

like image 845
Radu Rădeanu Avatar asked Dec 12 '22 12:12

Radu Rădeanu


2 Answers

#!/bin/bash    
n=0;#the variable that I want to be incremented
next_n=$[$n+1]
sed -i "/#the variable that I want to be incremented$/s/=.*#/=$next_n;#/" ${0}
echo $n
like image 171
eeeyes Avatar answered Dec 29 '22 12:12

eeeyes


A script is run in a subshell, which means its variables are forgotten once the script ends and are not propagated to the parent shell which called it. To run a command list in the current shell, you could either source the script, or write a function. In such a script, plain

(( n++ ))

would work - but only when called from the same shell. If the script should work from different shells, or even after switching the machine off and on again, saving the value in a file is the simplest and best option. It might be easier, though, to store the variable value in a different file, not the script itself:

[[ -f saved_value ]] || echo 0 > saved_value
n=$(< saved_value)
echo $(( n + 1 )) > saved_value

Changing the script when it runs might have strange consequences, especially when you change the size of the script (which might happen at 9 → 10).

like image 21
choroba Avatar answered Dec 29 '22 11:12

choroba