Search code examples
bashincrementauto-increment

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?


Solution

  • #!/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