1

Very new to Bash and pretty confused about local/global variables/subshells. I'm not sure why the modified variables won't print out at the end of the function—I'm trying to print out a final line count and file count at the end of the file, but if I do, it only prints out 0 because they are local variables. Is there any way to print out the modified values?

count=0
files=0
find . -type f | while IFC= read -r file;
do
   let files=files+1
   wc -l $file
   count=$(($count+$(wc -l < $file)))
   echo "total lines $count ; total files $files"
done
echo $files $count
exit 0

marked as duplicate by Michael Homer, terdon bash Nov 29 '17 at 18:36

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

Yes. But it is absolutely non-intuitive. This will work, for instance:

#!/bin/bash
count=0
files=0
while IFS= read -r file;
do
   let files=files+1
   wc -l $file
   count=$(($count+$(wc -l < $file)))
   echo "total lines $count ; total files $files"
done < <(find . -type f )
echo "$files $count"
exit 0

The <(command) construct is called "process substitution" and lets you treat the output of a command as a "file". Feeding it into the loop this way makes your script work as you expect.

The problem is your use of the pipe (|) which causes the while loop to run in a separate subshell which can't modify variables outside it.

In shells that don't support the <() feature, you can run the command(s) on the right of the pipe in a subsell and include the final echo in that subshell:

#!/bin/bash
files=0
find . -type f | {
    while IFC= read -r file;
    do
        let files=files+1
        wc -l $file
        count=$(($count+$(wc -l < $file)))
        echo "total lines $count ; total files $files"
    done
    echo "$files $count"
}

exit 0

Not the answer you're looking for? Browse other questions tagged or ask your own question.