1

我编写了一个名为“wp”的小 bash 脚本,它将文件上传到 ftp 服务器。它使用 wput 实用程序。它从文本文件中获取文件列表。上传准备好后,它会在文本文件中用双叉注释掉该行。根据日志文件的最后一行检测上传成功。我的问题是如何避免多次启动我的脚本?我正在尝试使用 pgrep 检测实例是否正在运行,但无法正常工作:

#!/bin/bash

if [ "$(pgrep ^wp$|wc -l)" -eq "2" ]

then 
  echo "$(pgrep ^wp$)"
  echo "$(pgrep ^wp$|wc -l)"
  echo "wp script is starting..."
else 
  echo "$(pgrep ^wp$)"
  echo "$(pgrep ^wp$|wc -l)"
  echo "wp script is already running!"
  exit
fi

server="ftp://username:password@ftp.ftpserver.com"
logfile=~/uploads.log
listfile=~/uploads.txt
list_backup=~/uploads_bak000.txt

while read f;
do
 ret=""

 if [ "${f:0:1}" = "#" -o "$f"1 = 1 ] 
 then
  if [ "$f"1 = 1 ] 
  then
   :
   #echo "invalid string: "$f
  else
   #first character is remark sign # then empty command -> :
   echo "remark line skipped: "$f 
  fi
 else
  #while string $ret is empty
  while [ -z "$ret" ]
  do
   wput "$f" --tries=-1 "$server" 2>&1|tee -a $logfile #> /dev/null
   ret=$(tail -n 1 "$logfile"|grep "FINISHED\|Nothing\|Skipped\|Transfered")
  done
  if [ -n "$ret" ]
  then
   cat $listfile > $list_backup
   awk -v f="$f" '{if ($0==f && $0!~/#/) print "#" $0; else print $0;}' $list_backup > $listfile
  fi
 fi 
done < $listfile
4

1 回答 1

2

有一些使用 ps 和 grep 的 quick-n-dirty 解决方案(不要这样做)。

最好将锁定文件用作“互斥锁”。一个很好的方法是使用目录作为锁定文件(http://mywiki.wooledge.org/BashFAQ/045)。

我还建议看一下: http://mywiki.wooledge.org/ProcessManagement#How_do_I_make_sure_only_one_copy_of_my_script_can_run_at_a_time.3F ,其中提到了使用抽象锁的setlockhttp://cr.yp.to/daemontools/setlock.html )为您处理文件。

于 2013-07-07T20:16:39.260 回答