Here is a minimal example of what I am trying to do:
# If it does not exist, create a file to persist the unique identifier
if [ ! -f ~/.uid ]; then
echo 0 > ~/.uid
fi
# Increment the unique identifier in the ~/.uid file
echo 1 + $(<~/.uid) | bc > ~/.uid
# Launch expensive computation that uses this unique identifier
uid=$(<~/.uid)
do_something_long $uid
Except, multiple instances of this script could be running at the same time, and do_something_long should be invoked with an unique identifier (preferably human-readable, so starting from 0 or 1).
I tried to use flock(1) for acquiring a lock, but most safe examples use a subshell to bind to a file descriptor, which prevent me to access the unique identifier in the parent shell. And I don't want do_something_long in the subshell, as it would hog the lock for too long.