linuxbashshellunix

Bash script wait if already running, then continue


I have a bash script that is called by a program once a process is complete. I need a way for that bash script to wait if another instance of itself is running to exit before continuing. I can't just use lock files and exit because the script will not be called again on any kind of regular schedule.


Solution

  • I can't just use lock files and exit because the script will not be called again on any kind of regular schedule.

    Within the script, before creating the lock file, you can loop through checking if the lock file exists, if it does, continue looping (through a sleep command or something) and when it goes away, create it.

    Something like:

    #!/bin/bash
    
    while [ -e /var/tmp/bash_script.lock ];
    do
        sleep 5
    done
    
    touch /var/tmp/bash_script.lock
    
    echo "do something"
    
    rm /var/tmp/bash_script.lock