Does export serve any purpose in this code?

I understand that it calculates the sum of the number of lines of all *.java files in the directory src.

This is not necessarily completely true. It calculates the sum of the number of lines of all *.java files in the directory tree rooted at src (i.e. src and all its child directories). But it will fail for any file paths containing whitespace or when there are directory names ending with .java.

Since SUM is never accessed by a child process, is there any reason for exporting it?

No.

I would probably write the snippet of code like this, making it filename-safe in the process:

find src -type f -name '*.java' -exec wc -l {} \; | awk '{ s += $1 } END { print s }'

A better solution would probably be this:

find src -type f -name '*.java' -exec cat {} + | wc -l

You're right, there is no need to use export here. There are more problems with this code though:

$  ~/.cabal/bin/shellcheck e.sh

In e.sh line 4:
for f in $(find src -name "*.java"); do
         ^------------------------^ SC2044: For loops over find output are fragile. Use find -exec or a while read loop.


In e.sh line 5:
    export SUM=$(($SUM + $(wc -l $f | awk '{ print $1 }')))
                  ^--^ SC2004: $/${} is unnecessary on arithmetic variables.
                                 ^-- SC2086: Double quote to prevent globbing and word splitting.

Did you mean:
    export SUM=$(($SUM + $(wc -l "$f" | awk '{ print $1 }')))

For more information:
  https://www.shellcheck.net/wiki/SC2044 -- For loops over find output are fr...
  https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...
  https://www.shellcheck.net/wiki/SC2004 -- $/${} is unnecessary on arithmeti...

And it's a good practice to use lowercase variable names in the scripts, see this for an explanation.

In general, tldp.org is not recommended, see this or this. I've also seen people not recommending tldp.org here at StackExchange.

Tags:

Shell Script