Shell – Script that outputs the total number of lines in all the text files that are passed as arguments

linuxscriptingshell-script

So I'm working on a script that will accept arguments that are text files, and should output the total number of lines in those files. 
For example, if I say

./myScript file1 file2 file3

it will print

10 total

(let us assume that the sum of all the lines from those three files is 10).

I know how to go over all the arguments. 
I also know that, to get the number of lines in a file, I would say:

wc -l < fileName

However, how can I make that into an "int" that I can add to some sort of cumulative sum?

Best Answer

You can accomplish your goal simply by using cat and a pipeline:

cat "$@" | wc -l

If you really wanted to sum manually, you can do this with awk:

for f in "$@"; do 
    wc -l < "$f"
done | awk '{ sum+=$1 } END { print sum }'

Or if you really wanted to parse the last line of wc, removing the string "total":

wc -l "$@" | awk 'END { print $1 }'
Related Question