变量在bash中递增,而循环在循环结束时重置为0

时间:2016-06-29 18:25:37

标签: bash loops while-loop

我正在编写一个bash脚本,它使用while循环来处理从特定命令输出的行。我还为找到的每一行增加一个变量(加1)。

下面是有问题的脚本部分的示例:

#!/bin/bash

count=0

ls | while read f
do 
  count=$(($count+1))
  echo "Count is at ${count}"
done

echo "Found total of ${count} rows"

基本上,它会增加$count变量,但是当我在while循环后打印$count时,它会重置为0 ..

示例输出:

Count is at 1
Count is at 2
Count is at 3
Count is at 4
Count is at 5
Found total of 0 rows

知道为什么$count会在循环完成后重置?

我还尝试在循环中使用&&运算符添加最后一个echo语句,如下所示:

count=0

ls | while read f
do 
  count=$(($count+1))
  echo "Count is at ${count}"
done && echo "Found total of ${count} rows"

没有成功。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

管道产生subshell,改为使用process substitutions

while read -r f
do 
  count=$(($count+1))
  echo "Count is at ${count}"
done < <(ls)

另请注意,您不应该parse the output of ls

您的示例似乎计算当前目录中的文件和目录的数量,可以使用find和wc来完成:

find -maxdepth 1 -mindepth 1 -printf "\n" | wc -l

或者你可以通过for循环和globbing来避免ls

for f in * .*; do
  [ -e "$f" ] || continue
  count=$((count + 1))
  echo "Count is at ${count}"
done