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”
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
It’s true bc is not always there to help. Thanks for your contribution & dropping a “thx”!
# echo 2 > /tmp/counter
# echo $(($(cat /tmp/counter)+3))
I’m pretty unclear with what’s going on exactly there, care to explain?