I have a script which has multiple functions, running in parallel which checks a file and updates it frequently. I dont want two functions to update the file at the same time and create an issue. So what will be the best way to have an atomic update. I have the following so far.
counter(){
    a=$1
    while true;do
        if [ ! -e /tmp/counter.lock ];then
            touch /tmp/counter.lock
            curr_count=`cat /tmp/count.txt`
            n_count=`echo "${curr_count}  + $a" | bc`
            echo ${n_count} > /tmp/count.txt
            rm -fv /tmp/counter.lock
            break
        fi
        sleep 1 
    done
}
I am not sure how to convert my function to use flock, since it uses file descriptor and it might create issue if I call this function multiple time(or I think so.)
 
     
    