计数器增量猛砸循环不工作 [英] Counter increment in Bash loop not working

查看:151
本文介绍了计数器增量猛砸循环不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在那里我运行一个循环以下简单的脚本,并希望保持一个 COUNTER 。我无法弄清楚为什么计数器不更新。它是由于子shell这就是越来越产生的?我怎么可能会解决这个问题?

 #!/斌/庆典WFY_PATH =在/ var /日志/ n​​ginx的
WFY_FILE = error.log中
COUNTER = 0
grep的GET / LOG_'$ WFY_PATH / $ WFY_FILE | grep的上游超时| awk的-F',''{打印$ 2,$ 4,$ 0}'| AWK'{打印http://domain.com$ 5&安培; IP =$ 2&放大器;日期=$ 7&放大器;时间=$ 8&放大器;年底= 1}'| awk的-F'和末端= 1''{打印$ 1&安培;年底= 1}'|

而读WFY_URL

    回声$ WFY_URL #Some更多行动
    COUNTER = $((COUNTER + 1))
DONE
)回声$#COUNTER输出= 0


解决方案

首先,你是不是增加了柜台。更改 COUNTER = $((COUNTER)) COUNTER = $((COUNTER + 1)) COUNTER = $ [COUNTER + 1] 将增加。

第二,它是棘手,你揣到后台传播子shell变量被调用者。在子shell变量不可用子shell之外。这些都是局部变量的子进程。

解决这个问题是使用临时文件存储的中间值的一种方式:

  TEMPFILE =的/ tmp / $$。TMP
呼应0 GT; $ TEMPFILE#环放在这里
  #获取的价值,增加其
  COUNTER = $ [$(猫$ TEMPFILE)+ 1]  #存储新值
  回声$ COUNTER> $ TEMPFILE#循环中完成,脚本完成,删除文件
断开链接$ TEMPFILE

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

解决方案

First, you are not increasing the counter. Changing COUNTER=$((COUNTER)) into COUNTER=$((COUNTER + 1)) or COUNTER=$[COUNTER + 1] will increase it.

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

这篇关于计数器增量猛砸循环不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆