如何重试bash命令直到状态正常或达到超时?
我最好的镜头(我正在寻找更简单的东西):
NEXT_WAIT_TIME=0
COMMAND_STATUS=1
until [ $COMMAND_STATUS -eq 0 || $NEXT_WAIT_TIME -eq 4 ]; do
command
COMMAND_STATUS=$?
sleep $NEXT_WAIT_TIME
let NEXT_WAIT_TIME=NEXT_WAIT_TIME+1
done
Run Code Online (Sandbox Code Playgroud) 我编写了一个运行命令的函数,它以两个args为第一个命令,以秒为单位的第二个超时:
#! /bin/bash
function run_cmd {
cmd="$1"; timeout="$2"
grep -qP "^\d+$" <<< "$timeout" || timeout=10
stderrfile=$(readlink /proc/$$/fd/2)
exec 2<&-
exitfile=/tmp/exit_$(date +%s.%N)
(eval "$cmd";echo $? > $exitfile) &
start=$(date +%s)
while true; do
pid=$(jobs -l | awk '/Running/{print $2}')
if [ -n "$pid" ]; then
now=$(date +%s)
running=$(($now - $start))
if [ "$running" -ge "$timeout" ];then
kill -15 "$pid"
exit=1
fi
sleep 1
else
break
fi
done
test -n "$exit" || exit=$(cat $exitfile)
rm $exitfile
exec 2>$stderrfile
return "$exit"
}
function …Run Code Online (Sandbox Code Playgroud) 对于执行存储在变量中的eval命令,使用命令:
???> a="echo -e 'a\nb' | wc -l"
???> eval $a
2
Run Code Online (Sandbox Code Playgroud)
但它如何与timeout命令结合?我试过以下哪个给了我错误的输出:
???> timeout 10 $a
'a
b' | wc -l
Run Code Online (Sandbox Code Playgroud)
以下给出了我的错误:
???> timeout 10 "$a"
timeout: failed to run command `echo -e \'a\\nb\' | wc -l': No such file or directory
???> timeout 10 $(eval $a)
timeout: failed to run command `2': No such file or directory
???> timeout 10 $(eval "$a")
timeout: failed to run command `2': No such file or directory
Run Code Online (Sandbox Code Playgroud)
问题还可以解决:我怎样才能确定以下命令是否正确执行? …