Shell scripting – updating a file holding a counter

counter=`cat /tmp/counter` ; echo "$counter+1" | bc > /tmp/counter

note that loading the /tmp/counter into the variable is a necessary indirection, the following:

echo "`cat /tmp/counter`+1" | bc > /tmp/counter

would not work as the output redirection gets triggered before the cat gets a chance to happen, so the file is emptied too early.

4 Replies to “Shell scripting – updating a file holding a counter”

  1. Since we’re dealing with integers, I would rather write:
    f=/tmp/counter; n=`cat $f | xargs expr 1 +`; echo $n > $f

    No need for bc this way. But you still need a variable though :/

    ps: thx for this blog, some articles really helped me

Leave a Reply

Your email address will not be published. Required fields are marked *