我正在编写一个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"
没有成功。
任何帮助将不胜感激
答案 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