I’m having some issues in a unix shell script I’m trying to write that keeps a running total of the number of lines in multiple files from the command line. I can count the lines individually and display them for each run through the loop but my lines variable always reads 0 at the end.
#! /bin/sh
lines=0
line_count(){
#count the lines
l= blablabla.....
lines=`lines + l`
}
for f in "$@"
do
echo "total lines:"
( line_count "$f" )
done
If you run something in a subshell, any variable changes you do (e.g. increasing
$lines) are only valid within that subshell and are lost when the subshell exits. But since you are using a function you don’t need a subshell at all, just call the function.Also
lines=`lines + l`will try to execute the commandlineswith arguments+andl, which I think is not what you intended. To evaluate the result of an expression, use the$(( ... ))syntax, and prepend$to your variables to work with their values.Finally you never use the value of
$lines, you may want to print it after you’ve called the function.