我試圖編寫一個腳本來驗證指標的所有統計信息都是正面的,然後再使用該服務進行任何更改。我被困在該部分在思考着如何尾巴以下用例的遞歸: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