Quick-and-dirty way to ensure only one instance of a shell script is running at a time

前端 未结 30 2420
忘掉有多难
忘掉有多难 2020-11-22 02:57

What\'s a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?

30条回答
  •  情歌与酒
    2020-11-22 03:06

    Actually although the answer of bmdhacks is almost good, there is a slight chance the second script to run after first checked the lockfile and before it wrote it. So they both will write the lock file and they will both be running. Here is how to make it work for sure:

    lockfile=/var/lock/myscript.lock
    
    if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null ; then
      trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
    else
      # or you can decide to skip the "else" part if you want
      echo "Another instance is already running!"
    fi
    

    The noclobber option will make sure that redirect command will fail if file already exists. So the redirect command is actually atomic - you write and check the file with one command. You don't need to remove the lockfile at the end of file - it'll be removed by the trap. I hope this helps to people that will read it later.

    P.S. I didn't see that Mikel already answered the question correctly, although he didn't include the trap command to reduce the chance the lock file will be left over after stopping the script with Ctrl-C for example. So this is the complete solution

提交回复
热议问题