我试图编写一个脚本来验证指标的所有统计信息都是正面的,然后再使用该服务进行任何更改。我被困在该部分在思考着如何尾巴以下用例的递归:Bash中的尾递归
function load_cache() {
cacheStat=($(curl -s -X GET "http://localhost:${MET_PORT}/metrics" | sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="cacheSize" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | grep -w "cacheSize" | cut -d ':' -f 2))
# the above gives me the ouput(cacheStat) as -
# 2.0
# 311.0
# 102.0
count=0
for index in ${!cacheStat[*]}
do
if [[ ${cacheStat[$index]} -le 0 ] && [ $count -lt 3 ]]; then
sleep .5
count=$[$count +1];
load_cache
#Wouldn't the above initialise `count` to 0 again.
fi
done
}
我所试图做的是,如果任何在cacheStat的元素小于或等于0
,然后睡眠.5
秒,然后再次查询cacheStat并再次检查其所有元素。虽然不是这样做超过3倍,我正在尝试使用`count。
对任何改进脚本的建议均可使用。
更新 - 在修改剧本由@Inian作为建议
RETRY_COUNT=0
function load_cache() {
cacheStat=($(curl -s -X GET "http://localhost:${MET_PORT}/metrics" | sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="cacheSize" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | grep -w "cacheSize" | cut -d ':' -f 2));
for index in ${!cacheStat[*]}
do
echo "Stat - ${cacheStat[$index]}"
if ((${cacheStat[$index]} <= 0)) && (($RETRY_COUNT < 3)); then
echo "Attempt count - ${RETRY_COUNT}"
sleep .5s
RETRY_COUNT=$((RETRY_COUNT +1));
load_cache
fi
done
}
日志阅读 -
> > + cacheStat=($(curl -s -X GET "http://localhost:${MET_PORT}/metrics" | sed 's/\\\\\//\//g' | sed
> 's/[{}]//g' | awk -v k="cacheSize"
> > '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed
> > 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | grep -w
> > "cacheSize" | cut -d ':' -f 2))
> > ++ curl -s -X GET http://localhost:8181/metrics
> > ++ sed 's/\\\\\//\//g'
> > ++ sed 's/[{}]//g'
> > ++ sed 's/[\,]/ /g'
> > ++ awk -v k=cacheSize '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}'
> > ++ sed 's/\"\:\"/\|/g'
> > ++ cut -d : -f 2
> > ++ sed 's/\"//g'
> > ++ grep -w cacheSize
,它甚至没有重复我猜。
你的脚本有一些语法问题。修复它之前尝试回来,你确定这工作? – Inian
@Inian它没有。这就是分享它的原因。请你指出缺陷。考虑一下我是一个新手bash。试图执行脚本,我只能看到直到'count = 0',并且没有任何提示。即使我在那里放了一个“回声”。 – nullpointer
请参考下面的答案,首先通过在函数外移动count来移除无限递归。 – Inian