You cannot pass variables from forked/backgrounded scripts to their parents or siblings, so basically you need to use a different method. Here I store your counter in the filesystem.
I chose to use Perl because I want to use its flock()
function which allows me to lock the file containing the counter for exclusive access by a single process at a time - that way you avoid race conditions between the multiple, parallel processes.
So, save the following little Perl script as BumpCounter
#!/usr/bin/perl
use strict;
use warnings;
use Fcntl qw(:seek :flock);
# Open counter file /tmp/counter.txt
open my $fh, '+<', '/tmp/counter.txt' or die "Couldn't open file: $!";
# Lock it for exclusive access
flock($fh,LOCK_EX) or die "couldn't get lock: $!\n";
# Read current value
my $cnt=<$fh>;
# Increment value and write back
seek($fh,0,SEEK_SET);
printf $fh ++$cnt;
# Close handle
close $fh;
Then make it executable by running the following command:
chmod +x BumpCounter
Then inside your do-something
script you would do
# do some work
./BumpCounter
# do some work
To see the counter's value, just do
cat /tmp/counter.txt
To test it, zero the counter, start 500 do-something
s in the background, then check the counter like this:
echo 0 > /tmp/counter.txt
for j in {0..499}; do
./do-something &
done
cat /tmp/counter.txt
500
If you like this approach, the script could be adapted to accept a parameter, so that it could work like this:
./Counter RESET # reset counter to zero
./Counter READ # read counter's current value
./Counter +3 # add 3 to counter
./Counter -1 # subtract 1 from counter