More Bash Scripting

When trying to write a simple one-liner that counted lines of code in a source subdirectory, I finally came up with the following:

export SUM=0;for f in $(find src -name "*.java"); do export SUM=$(($SUM + $(wc -l $f | awk '{ print $1 }'))); done; echo $SUM

This has the distinction of using the Bash arithmetic operator $(()) or $[[]]. Basically, it creates a variable called SUM, then internally loops around for each file name returned by the find command. It then passes the filename to wc -l to count the lines, and then to awk to strip out everything but the line count. This sequence of commands is encapsulated into a variable using command substitution (the $() bit), and used in conjunction with the arithmetic operator ($(())) to update the add the current line count to the existing SUM variable.

Of course, this is a crude attempt to count LOC, and is probably more suited for more general counting, since it does not take into account blank lines, comments, etc.

Leave a Reply