1

Before I reach for my editor and write a small tool myself:

Is there a simple unix/gnutool that can increment numbers persistently. Something along the lines of:

  $ increment 
  #=> 1
  $ increment
  #=> 2
  $ exit
  $ increment
  #=> 4

It can store the number on disk (~/.increment) or anywhere else. Bonuspoints for "named" numbers, like $ increment --name=foo; where there are incrementers per name.

berkes
  • 26,996
  • 27
  • 115
  • 206

1 Answers1

2
#!/bin/bash

readonly myfile=${0%.sh}.store

[[ ! -s $myfile ]] echo '0' >> $myfile

read myid < $myfile
((++myid))

echo $myid
echo $myid > $myfile
bobah
  • 18,364
  • 2
  • 37
  • 70
  • Exercise for the reader: count the number of race conditions. Run this 1000 times synchronously and count how many duplicates are generated. How many values are skipped? What could be done to improve this script? – William Pursell Nov 14 '12 at 16:49
  • @WilliamPursell - answer: http://stackoverflow.com/questions/185451/quick-and-dirty-way-to-ensure-only-one-instance-of-a-shell-script-is-running-at, or any similar topic on SO, there are plenty of them – bobah Nov 14 '12 at 17:10