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?

elyashiv
  • 767

1 Answers1

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.

Mat
  • 52,586