How do I make sure my bash script isn't already running?

后端 未结 13 842
無奈伤痛
無奈伤痛 2020-12-31 05:56

I have a bash script I want to run every 5 minutes from cron... but there\'s a chance the previous run of the script isn\'t done yet... in this case, i want the new run to j

13条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 06:34

    If you use a lockfile, you should make sure that the lockfile is always removed. You can do this with 'trap':

    if ( set -o noclobber; echo "locked" > "$lockfile") 2> /dev/null; then
      trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT
      echo "Locking succeeded" >&2
      rm -f "$lockfile"
    else
      echo "Lock failed - exit" >&2
      exit 1
    fi
    

    The noclobber option makes the creation of lockfile atomic, like using a directory.

提交回复
热议问题