为什么不是我的变量似乎在我的bash while循环递增? [英] Why doesn't my variable seem to increment in my bash while loop?

查看:111
本文介绍了为什么不是我的变量似乎在我的bash while循环递增?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的bash脚本编程。我似乎无法让我的计算变量的正确值在我的bash脚本一个,而循环的末尾显示。

I am fairly new to bash scripting. I can't seem to get the correct value of my counting variables to display at the end of of a while loop in my bash script.

背景:我有一个相当简单的任务:我想传递一个包含的文件路径bash脚本列表的文本文件,有它检查这些文件的存在,算上现有的/丢失的文件的数量。我得到大部分的脚本的工作,除了计数部分。

Background: I have a fairly simple task: I would like to pass a text file containing a list of file paths to a bash script, have it check for the existence of those files, and count the number of existing/missing files. I got most of the script to work, except for the counting part.

N=0
correct=0
incorrect=0
cat $1 | while read filename ; do
    N=$((N+1))
    echo "$N"

    if ! [ -f $filename ]; then

        incorrect=$((incorrect+1))
    else
        correct=$((correct+1))

    fi

done

echo "# of Correct Paths: $correct"
echo "# of Incorrect Paths: $incorrect"
echo "Total # of Files: $N"

如果我有5个文件,其中4存在的名单,我希望得到下面的输出(注意内的回声命令循环):

If I have a list of 5 files, 4 of which exist, I expect to get the following output (note the echo command within the while loop):

1
2
3
4
5
# of Correct Paths: 4
# of Incorrect Paths: 1
Total # of Files: 5

相反,我得到:

1
2
3
4
5
# of Correct Paths: 0
# of Incorrect Paths: 0 
Total # of Files: 0

发生了什么事,这些变量的值?谷歌有质量问题的许多建议,我想我能得到它多一点的搜索工作,但我做错了一个简要的解释将是非常有益的。

What happened to the values of these variables? Google had many suggestions of questionable quality and I think I could get it to work with a little more searching, but a brief explanation of what I'm doing wrong would be very helpful.

推荐答案

这是因为你使用的是无用的命令与管道,造成子shell要创建。尝试没有

This is because you are using the useless cat command with a pipe, causing a subshell to be created. Try it without the cat:

while read filename ; do
    N=$((N+1))
    ....
done < file

这篇关于为什么不是我的变量似乎在我的bash while循环递增?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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