bashunixlockfile

Prevent other terminals from running a script while another terminal is using it


I would like prevent other terminals from running a certain script whenever another terminal is running it however in bash but I'm not quite sure on how I would be able to go about in doing it. Any help or tip could be greatly appreciated!

In example: When that script is being run on another terminal, all other terminals would be unable to run that certain script as well. And display a message "UNDER MAINTENANCE".


Solution

  • You can use the concept of a "lockfile." For example:

    if [ -f ~/.mylock ]; then
        echo "UNDER MAINTENANCE"
        exit 1
    fi
    touch ~/.mylock
    
    # ... the rest of your code
    
    rm ~/.mylock
    

    To get fancier/safer, you can "trap" the EXIT signal to remove it automatically at the end:

    trap 'rm ~/.mylock' EXIT