问题描述:设置在定时任务中的脚本一定要注意防止脚本重复执行,要不然会带来一些想象不到的结果。

方式一:使用锁定文件的方式来进行防止脚本重复运行,类似数据库socket文件,但是这种情况有一种弊端就是,如果脚本因为某些原因退出,但是lock文件没有被清理掉,就会导致下一次的脚本运行失败

#get script name
script_name=$(basename --"$0")

#get scriptlock file
lock_file="/tmp/$script_name.lock"

# Checkif scriptis run repeatedlyif [ -f $lock_file ]; then
  echo"`date '+%Y-%m-%d %H:%M:%S'` Another instance of $script_name is already running. Exiting." | tee -a $mylogfile
  exit1else 
  touch $lock_file
fi
# 程序执行体 # Delete scripts
lock file find $lock_file-delete2>&1 | tee -a $mylogfile

方式二:使用过滤脚本进程个数的方式判断脚本是否正在运行,这种方式要注意在脚本头一定要加上#!/bin/bash,否则系统可能会识别成为一个程序执行体,并不是一个脚本,导致过滤的时候有问题

#!/bin/bash
check_scripts() { #
get script name script_name=$(basename --"$0") #get script counts running_scripts=$(pgrep -fc"$script_name") # check the number of scriptsif (( running_scripts >1 )); then echo"`date '+%Y-%m-%d %H:%M:%S'` Another instance of $script_name is already running. Exiting." exit1 fi } # Checkif scriptis run repeatedly check_scripts