Just annotations of little "how to's", so I know I can find how to do something I've already done when I need to do it again, in case I don't remember anymore, which is not unlikely. Hopefully they can be useful to others, but I can't guarantee that it will work, or that it won't even make things worse.
Make bash scripts wait in line until other instances have finished their job
Code:
#!/bin/bash # It seems to work, but who knows. May have some terrible flaw and ruin your life. Your entire life. # # "${0##*/}" is the script name ("$0") stripped of any parameters ("##*/"), by the way. # if ls /dev/shm/${0##*/}-ticket* 2> /dev/null ; then n=0 while [[ -e "/dev/shm/${0##*/}-ticket$n" ]]; do n=$(( $n + 1 )) done touch /dev/shm/${0##*/}-ticket$n echo there are $n scripts in line... lastinst=$(( $n - 1)) while true ; do sleep $((2*$n)) [[ ! -f "/dev/shm/${0##*/}-ticket$lastinst" ]] && break done else echo no scripts in line touch /dev/shm/${0##*/}-ticket0 n=0 fi # i=$((n+1)) # replace the following with an actual script that matters # # BUT DON'T FORGET TO ADD THE "RM" LINE AT THE END # # I wonder if it can be used as a script to put any other script in line like a command, # like "ticket.sh anotherscript/program" if in the end it runs $@ or $*. Got to think more # about that and test it someday. # # May need some sort of trap for orphaned tickets/lock files # ### ACTUAL SCRIPT COMES HERE ### time=$(seq 1 5 | shuf -n 1) sleep $time echo instance $n done, slept $time ####### END OF ACTUAL SCRIPT ######## ### GET RID OF THE LOCK FILE AFTER THE SCRIPT IS DONE ### # otherwise the next instances won't ever really run! rm /dev/shm/${0##*/}-ticket$n
$ test.sh & sleep 0.5 && test.sh & sleep 0.6 && test.sh & sleep 0.4 && test.sh & sleep 0.6 && test.sh & sleep 0.7 && test.sh && echo all done!!
I guess it can have some trouble if it's started in parallel at the same time, like "script.sh & script.sh & script.sh", but if there's some wait between each execution there should be no problem, I guess -- but I'm not sure.
Total Comments 0