如何根据 if 语句的结果终止 pid

如何根据 if 语句的结果终止 pid

如果程序仅与一个 pid 关联(它必须有两个 pid),我试图让它重新启动。如果有多个 pid 则可以,我试图编写一个 bash 脚本来执行此操作,但我很难使其正常工作,这是我的代码,所以,有人可以帮助我实现我的目标吗?

#! /bib/bash
pgrepRes=($(pgrep deluge))
if ["${#pgrepRes[@]}" -ne "2"];
    then
        kill ${pgrepRes[0]};
fi
deluge

但我得到了这个结果:

正如你所见,我检查了有多少个 pid 与 Deluge 相关联。

提前致谢,希望我说得足够清楚,否则,请询问:)

答案1

有一些印刷错误。尝试这样做

#!/bin/bash
pgrepN=$( pgrep deluge | wc -l )
if [ "$pgrepN" -lt  "2" ]; then
   echo "less then 2"         # pkill deluge
   echo here restart deluge   # restart only if there were less than 2
fi

请注意,在 shebang (第一行) 中,您不应在#!和 shell 的路径之间放置空格,使用测试运算符时,[]您需要在括号内放置空格:例如,这是[ OK ] 中的这个[NOT OK]
如果我正确理解了您的目的,您只想在出现次数少于 2 次时重新启动,因此在 IF 语句内。


更新

#!/bin/bash
Time_to_Sleep="5m"                      # Put here the amount of time
DKiller="/tmp/Kill_Deluge_Script.sh"    # Put here the deluge killer script Name

echo "#!/bin/bash"         >  $DKiller  # Creating script that will kill this one
echo "kill $$; sleep 3s; " >> $DKiller  # Passing the command to kill this one
echo "pkill deluge"        >> $DKiller  # Now you can kill deluge too
echo "echo deluge killed... RIP " >>   $DKiller
chmod u+x $DKiller                      # Make the script executable for you

while true 
do
  pgrepN=$( pgrep deluge | wc -l )
  if [ "$pgrepN" -lt  "2" ]; then
     echo "less then 2"         # pkill deluge
     echo here restart deluge   # restart only if there were less than 2
  fi
sleep $Time_to_Sleep
done

相关内容