【发布时间】:2017-03-01 08:48:24
【问题描述】:
在使用该服务进行任何进一步更改之前,我尝试编写一个脚本来验证指标的所有统计数据是否为正。我坚持的部分是考虑如何为以下用例尾随递归:
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 没有。这就是为什么要分享它。并且请您指出其中的缺陷。把我当成一个 bash 的新手。尝试执行脚本时,我看到的只是
count=0,之前什么都没有。即使我把echo放在那里。 -
参考下面我的答案,首先通过将
count移到函数外来消除无限递归。 -
看起来你无论如何都在模糊地硬编码一个穷人的 JSON 解码器。尝试转向支持 JSON 的语言,例如
jq。 -
如果你的意思是
sedsn-p,这有点投机。如果您需要支持浮点,则正则表达式需要稍微复杂一些。无论如何,为了便于阅读,我仍然会选择jq。
标签: bash recursion tail-recursion