Bash循环中的计数器增量不起作用 [英] Counter increment in Bash loop not working
问题描述
我有以下简单的脚本,我在其中运行一个循环并希望维护一个 COUNTER
.我无法弄清楚为什么计数器没有更新.是因为创建了子shell吗?我该如何解决这个问题?
I have the following simple script where I am running a loop and want to maintain a COUNTER
. I am unable to figure out why the counter is not updating. Is it due to subshell thats getting created? How can I potentially fix this?
#!/bin/bash
WFY_PATH=/var/log/nginx
WFY_FILE=error.log
COUNTER=0
grep 'GET /log_' $WFY_PATH/$WFY_FILE | grep 'upstream timed out' | awk -F ', ' '{print $2,$4,$0}' | awk '{print "http://domain.com"$5"&ip="$2"&date="$7"&time="$8"&end=1"}' | awk -F '&end=1' '{print $1"&end=1"}' |
(
while read WFY_URL
do
echo $WFY_URL #Some more action
COUNTER=$((COUNTER+1))
done
)
echo $COUNTER # output = 0
推荐答案
首先,您没有增加计数器.将 COUNTER=$((COUNTER))
更改为 COUNTER=$((COUNTER + 1))
或 COUNTER=$[COUNTER + 1]
会增加.
First, you are not increasing the counter. Changing COUNTER=$((COUNTER))
into COUNTER=$((COUNTER + 1))
or COUNTER=$[COUNTER + 1]
will increase it.
其次,将子shell 变量反向传播给被调用者是比较棘手的.子外壳中的变量在子外壳之外不可用.这些是子进程的局部变量.
Second, it's trickier to back-propagate subshell variables to the callee as you surmise. Variables in a subshell are not available outside the subshell. These are variables local to the child process.
一种解决方法是使用临时文件来存储中间值:
One way to solve it is using a temp file for storing the intermediate value:
TEMPFILE=/tmp/$$.tmp
echo 0 > $TEMPFILE
# Loop goes here
# Fetch the value and increase it
COUNTER=$[$(cat $TEMPFILE) + 1]
# Store the new value
echo $COUNTER > $TEMPFILE
# Loop done, script done, delete the file
unlink $TEMPFILE
这篇关于Bash循环中的计数器增量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!