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/bashecho $1len=0cat $1 | while read linedo    let len+=${#line}    echo $lendoneecho $lenthe output is the following:xyz.sh111118275153707983920why doesn't len stays changed after the loop, and hoe to make it to do so?
bash script var not changed after the loop
bash
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 linedo    let len+=${#line}    echo $lendone < $1This doesn't require a subshell, so changes to $len will be visible in the parent.