Count Lines of Source Code using cloc on Raspberry Pi

Count Lines of Source Code using cloc on Raspberry Pi

The cloc is a command line tool that allows to count blank lines, comment lines, and physical lines of source code. Results are displayed in the table. This tool supports various programming languages.

This tutorial explains how to install and use cloc on Raspberry Pi.

Install cloc

Connect to Raspberry Pi via SSH. Retrieve the latest version tag of cloc release from GitHub. Assign version tag to variable.

CLOC_VERSION=$(curl -s "https://api.github.com/repos/AlDanial/cloc/releases/latest" | grep -Po '"tag_name": "v\K[0-9.]+')

The cloc is a single Perl script. Download script from releases page of the cloc repository and place it to /usr/local/bin directory.

sudo curl -Lo /usr/local/bin/cloc "https://github.com/AlDanial/cloc/releases/latest/download/cloc-${CLOC_VERSION}.pl"

Add required permissions to allow execute the script.

sudo chmod a+x /usr/local/bin/cloc

We can check cloc version:

cloc --version

Testing cloc

We need a source code for testing. So create a main.c file:

nano main.c

Add the following code:

#include <stdio.h>

// Hello world program
int main() {
    printf("Hello world\n");

    return 0;
}

Now run cloc command to count lines of code:

cloc main.c

You will get the following results:

       1 text file.
       1 unique file.
       0 files ignored.

github.com/AlDanial/cloc v 1.90  T=0.04 s (26.5 files/s, 211.7 lines/s)
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
C                                1              2              1              5
-------------------------------------------------------------------------------

The cloc is able to use compressed files. Download the .tar.gz file of the source code from GitHub:

sudo curl -Lo cloc.tar.gz "https://github.com/AlDanial/cloc/archive/master.tar.gz"

Run cloc command and provide .tar.gz file as argument:

cloc cloc.tar.gz

We can also provide directory that contains a source code.

tar xf cloc.tar.gz
cloc cloc-master

Uninstall cloc

If cloc is no longer needed, you can remove a script file:

sudo rm -rf /usr/local/bin/cloc

Leave a Comment

Cancel reply

Your email address will not be published.