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?
#!/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
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).
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