1

I'm quite new to bash scripting, and I wrote the following script to emulate the wc -c command: (I know it doesn't count the end of the line)

#!/bin/bash

echo $1
len=0
cat $1 | while read line
do
    let len+=${#line}
    echo $len
done
echo $len

the output is the following:

xyz.sh
11
11
18
27
51
53
70
79
83
92
0

why doesn't len stays changed after the loop, and hoe to make it to do so?

marked as duplicate by manatwork, Patrick, jasonwryan, slm, Bernhard Nov 2 '13 at 18:30

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.

3

That happens because your while loop is being run in a subshell. Variable modifications in the subshell don't affect the parent.

Avoid both the pipe and the useless use of cat by doing some redirection instead:

while read line
do
    let len+=${#line}
    echo $len
done < $1

This doesn't require a subshell, so changes to $len will be visible in the parent.

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