LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Blogs > linux-related notes
User Name
Password

Notices


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.
Rate this Entry

Make bash scripts wait in line until other instances have finished their job

Posted 08-06-2015 at 03:04 PM by the dsc
Updated 08-06-2015 at 06:34 PM by the dsc

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
Can test with something like:

$ 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.
Posted in Uncategorized
Views 504 Comments 0
« Prev     Main     Next »
Total Comments 0

Comments

 

  



All times are GMT -5. The time now is 10:52 PM.

Main Menu
Advertisement
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration