1

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
3
  • What's wrong with wc -l file? Commented Nov 30, 2012 at 12:43
  • You just want sh or you don't have access to wc, How about grep -c '.*' Commented Nov 30, 2012 at 12:51
  • I have the script how I want it, I just don't understand this whole sub shell thing that I believe is the cause of my counter not keeping track like it should. Commented Nov 30, 2012 at 12:53

1 Answer 1

3

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 command lines with arguments + and l, 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.

#! /bin/sh
lines=0

line_count(){
    #count the lines
    l= blablabla.....
    lines=$(( $lines + $l ))
}

for f in "$@"
do
    line_count "$f"
    echo "total lines: $lines"
done
Sign up to request clarification or add additional context in comments.

2 Comments

Would it be bad to just save the running total to a file and then grab the values out of there when I need them? Is that bad practice?
@jimjohnjim, it can be done that way but it would be much more efficient to keep the data in memory, especially for cases like this where you store a single number. For more complex tasks it may be necessary or helpful to write partial results to file for use later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.