shell 在特定时间执行命令并在特定时间或条件验证后结束命令

hc8w905p  于 2023-05-18  发布在  Shell
关注(0)|答案(1)|浏览(158)

我正在尝试以编程方式执行并杀死一个进程。

command... | at 8:00
TASK_PID=$!
kill $TASK_PID | at 5:00

我应该可以在早上8点开始命令,下午5点停止命令,对吧?
如果这段代码是正确的,我想添加3个条件,检查文件的最后几行,并在条件被验证的情况下杀死进程。我知道我应该使用命令tail,然后检查返回的字符串是否包含我要查找的字符串。
大致应该是这样的:

STR = tail -f $FILE

if [[ $STR == *"Condition1"* ]]; then
  kill $TASK_PID
fi

 if [[ $STR == *"Condition2"* ]]; then
      kill $TASK_PID
    fi

 if [[ $STR == *"Condition3"* ]]; then
      kill $TASK_PID
    fi

有人能帮帮我吗

hmae6n7t

hmae6n7t1#

而不是kill $TASK_PID | at 5:00,你应该把kill命令保留在上面的cleanup.sh脚本中,它们嵌套在你的条件中。
当然,您需要存储command的PID以便稍后杀死它。一些带有可选参数...command在上午8点运行的示例语法是command ... & echo $! > pidfile | at 8:00。这会将PID通过管道传输到名为pidfile的文件中。
然后运行./cleanup.sh pathToFile pathToPIDFile | at 17:00(24小时格式或指定AM/PM)。
因此,假设它们都位于同一目录中,则启动cleanup.sh以在下午5点检查某个testfile文件的命令将是./cleanup.sh testfile pidfile | at 17:00
下面是cleanup.sh的代码:

#$1 is the testfile passed as an argument
#& creates tail as a background process that terminates when finished
STR=$(tail $1 &)

#$2 is the pidfile passed as an argument
PID=$(cat pidfile)

if [[ "$STR" == *"Condition1"* ]]; then
    kill -9 $PID
fi

if [[ "$STR" == *"Condition2"* ]]; then
    kill -9 $PID
fi

if [[ "$STR" == *"Condition3"* ]]; then
    kill -9 $PID
fi

对于其他人,请注意双[[括号条件不符合POSIX,这些条件可能必须重写才能与不同的(非bash)shell一起工作。

相关问题