Linux bash-按错误或超时关闭脚本
在stackoverflow上有许多解决方案—如何通过超时关闭脚本或在出现错误时关闭脚本。 但如何将这两种方法结合起来呢? 如果在脚本执行期间出现错误-关闭脚本。 如果超时是关闭脚本 我有以下代码:Linux bash-按错误或超时关闭脚本,linux,bash,shell,Linux,Bash,Shell,在stackoverflow上有许多解决方案—如何通过超时关闭脚本或在出现错误时关闭脚本。 但如何将这两种方法结合起来呢? 如果在脚本执行期间出现错误-关闭脚本。 如果超时是关闭脚本 我有以下代码: #!/usr/bin/env bash set -e finish_time=$1 echo "finish_time=" ${finish_time} (./execute_something.sh) & pid=$! sleep ${finish_time} kill $pid 但如果
#!/usr/bin/env bash
set -e
finish_time=$1
echo "finish_time=" ${finish_time}
(./execute_something.sh) & pid=$!
sleep ${finish_time}
kill $pid
但如果在执行时出现错误,脚本仍在等待,则超时时间将结束 首先,我不会使用
set-e
你将明确地等待你想要的工作;wait
的退出状态将是作业本身的退出状态
echo "finish_time = $1"
./execute_something.sh & pid=$!
sleep "$1" & sleep_pid=$!
wait -n # Waits for either the sleep or the script to finish
rv=$?
if kill -0 $pid; then
# Script still running, kill it
# and exit
kill -s ALRM $pid
wait $pid # exit status will indicte it was killed by SIGALRM
exit
else
# Script exited before sleep
kill $sleep_pid
exit $rv
fi
这里有轻微的比赛情况;内容如下:
wait-n
在sleep
退出后返回,表示脚本将自行退出理想情况下,
wait
将设置一些shell参数,指示哪个进程导致它返回。因此,在子进程上设置一个超时。如果您等待的时间较短,则finish\u time
,并且child的退出状态为零,则等待到finish\u time
。如果子状态为非零,则退出并出错。如果等待时间过长且超时,则执行其他操作。如果您使用的是现代Linux(使用GNU coreutils),则会有一个timeout
命令为您执行所有这些操作。运行timeout“$finish\u time”。/execute\u something.sh
你就在这里了。