bash 如何使脚本在特定时间后运行后自行终止?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32704196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:36:14  来源:igfitidea点击:

How to make a script kill itself after running after a specific time?

bashshellubuntukillkill-process

提问by Mona Jalal

I have this script:

我有这个脚本:

#!/bin/sh

echo "Start: " $(date +%s)
(time hive --hiveconf mapreduce.job.reduce.slowstart.completedmaps=0.5 --hiveconf mapred.reduce.tasks=10 --hiveconf mapreduce.reduce.shuffle.parallelcopies=15 --hiveconf hive.execution.engine=mr -f sample-queries-tpcds/query50.sql --database tpcds_text_db_1_10) 2> output/tpcds_query_2c_50_mr.out
echo "End: " $(date +%s)

How can I add some code inside it so that it will kill itself say after 5 seconds of execution? (like after 5 seconds of ./script.sh )?

如何在其中添加一些代码,以便在执行 5 秒后它会杀死自己?(比如 ./script.sh 5 秒后)?

采纳答案by chepner

Just run hivein the background, then go to sleep for 5 seconds and kill hivewhen sleepexits. If hivehas already completed, killwill print an error message, but you can redirect it to /dev/nullto ignore it.

只需hive在后台运行,然后进入睡眠状态 5 秒,退出hive时杀死sleep。如果hive已经完成,kill将打印一条错误消息,但您可以将其重定向/dev/null到忽略它。

hive --hiveconf mapreduce.job.reduce.slowstart.completedmaps=0.5 \
     --hiveconf mapred.reduce.tasks=10 \
     --hiveconf mapreduce.reduce.shuffle.parallelcopies=15 \
     --hiveconf hive.execution.engine=mr \
     -f sample-queries-tpcds/query50.sql \
     --database tpcds_text_db_1_10) \
     2> output/tpcds_query_2c_50_mr.out & hive_pid=$!

sleep 5 & wait
kill $hive_pid 2> /dev/null

回答by John1024

This script will kill itself after 5 seconds:

此脚本将在 5 秒后自行终止:

#!/bin/sh
echo "Start: " $(date +%s)
sleep 5s && kill $$ &
while sleep 1; do echo Working; done
echo "End: " $(date +%s)

The pipeline sleep 5s && kill $$is run in the background and issues a kill after 5 seconds.

管道sleep 5s && kill $$在后台运行并在 5 秒后发出终止。

Your command, which could be hive, runs in the foreground. In the example above, I used a while-loop because it allows easy demonstration that the concept works. Substituting in your hive command results in:

您的命令(可能是hive)在前台运行。在上面的例子中,我使用了一个 while 循环,因为它可以很容易地证明这个概念是有效的。替换您的 hive 命令会导致:

#!/bin/sh
echo "Start: " $(date +%s)
sleep 5s && kill $$ &
(time hive --hiveconf mapreduce.job.reduce.slowstart.completedmaps=0.5 --hiveconf mapred.reduce.tasks=10 --hiveconf mapreduce.reduce.shuffle.parallelcopies=15 --hiveconf hive.execution.engine=mr -f sample-queries-tpcds/query50.sql --database tpcds_text_db_1_10) 2> output/tpcds_query_2c_50_mr.out
echo "End: " $(date +%s)