I have a cron that I am writing that will repeat every hour, and I need a simple way to pass a counter from the last run to the next run.

My plan was to add the number to a file at the end, and then call it back at the beginning, e.g.

At end of the first cron run:

echo $INC_COUNT > inc_counter.txt

Then at the start of the second run:


So far so good, but now I need to increment that number. I tried:


neither of which worked. What is the best way to increment this number?

  • 3
    Your NEW_INC_COUNTER is 1+1 string. If you want to add integer to variable, you can write it this way: NEW_INC_COUNTER=$((OLD_INC_COUNTER+1)). BTW: i++ equivalent from C language in bash is $((i++)). – patryk.beza Jul 8 '15 at 16:06

The following methods will work:

  1. NEW_INC_COUNTER=$((OLD_INC_Counter+1))
  2. ((NEW_INC_COUNTER = OLD_INC_Counter+1))
  3. ((OLD_INC_Counter+=1))
  4. ((OLD_INC_Counter++))
  5. let "NEW_INC_COUNTER = OLD_INC_Counter+1"
  6. let "OLD_INC_Counter+=1"
  7. let "OLD_INC_Counter++"

Good luck!

  • Also, NEW_INC_COUNTER=$(expr "$OLD_INC_Counter" + 1).  The spaces before and after the + are required.  Note, that, unlike the above, this will work if you fall into a time warp and come out in the 1980s.  (Except, strictly speaking, you would need to use NEW_INC_COUNTER=`expr "$OLD_INC_Counter" + 1`; the $(…) syntax wasn't invented until a few years later.)  (Oh, there are also solutions featuring echo … | bc and echo … | dc.) – G-Man Jul 9 '15 at 2:33
  • cheers for that, they worked perfectly, – IGGt Jul 9 '15 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.