linux - Bash循环中的计数器增量不起作用

我有以下简单的脚本,我在其中运行一个循环并想要维护一个 COUNTER。我无法弄清楚为什么计数器没有更新。是因为创建了子shell吗?我该如何解决这个问题?

#!/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.example"$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]会增加。

其次,根据您的推测,将子shell 变量反向传播给被调用者会比较棘手。子shell 中的变量在子shell 之外不可用。这些是子进程的本地变量。

解决它的一种方法是使用临时文件来存储中间值:

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

https://stackoverflow.com/questions/10515964/

相关文章:

linux - 使用 awk 保存修改

python - python,del或delattr哪个更好?

linux - 什么进程正在使用我所有的磁盘 IO

python - 在 python shell 中按箭头键时看到转义字符

linux - 大量文件的快速 Linux 文件计数

python - 递归删除python中的文件夹

linux - 查找和复制文件

python - 在python中通过分隔符拆分字符串

python - 我在 python 中遇到关键错误

c - C 到毫秒是否有替代 sleep 功能?