Counting lines of code on the command line

Yes, I know, counting lines of code is an evil thing to do to assess a code base, but I find it still interesting in many cases. Here is a simple bash function to count the lines of code in files that have specific file extensions:

function loc
{
    if [ "$#" -lt 1 ]
    then
        local path="."
        local search_pattern=".*"
    else
        local path=$1
        shift

        if [ "$#" -lt 1 ]
        then
            local search_pattern=".*"
        else
            local search_pattern=".*/\(.*\.$1\)"

            shift

            for extension in "$@"
            do
                search_pattern="$search_pattern\|\(.*\.$extension\)"
            done
        fi
    fi

    find $path -regex "$search_pattern" -print0 | wc -l --files0-from=- | sort -n
}

If you add this function to the .bashrc file in your home directory, you can type loc in a terminal to count the lines of code. If you do not provide any arguments when calling the function all files in the current working directory (and recursively in the sub-directories) are counted. You can, however, specify a directory to search in as well as a list of file extensions to filter the files:

# count all files in the current directory (and recursively in the sub-directories)
loc
# count files in the directory called 'src' (and its sub-directories)
loc src/
# as above, but count lines of files ending with '.java' or '.py' only
loc src/ java py