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
How to make a script kill itself after running after a specific time?
提问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 hive
in the background, then go to sleep for 5 seconds and kill hive
when sleep
exits. If hive
has already completed, kill
will print an error message, but you can redirect it to /dev/null
to 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)