[Git][Clangformat] Apply clang format to all modified files

function cformatgit(){
    gitdir=`git rev-parse --show-toplevel`
    if [ "$?" -ne "0" ] ; then
        echo "Cannot get git root dir"
        return 
    fi

    echo "Format ($gitdir):"
    allfiles=`git diff --name-only`
    for fl in $allfiles ; do
        extfl="${fl##*.}"
        if [ "$extfl" == "hpp"  ] || [ "$extfl" == "h"  ] || [ "$extfl" == "cpp"  ] ; then
            if [ -f "$gitdir/$fl" ] ; then
                echo "Format "$gitdir/$fl" ($extfl)"
                clang-format -i "$gitdir/$fl"
                if [ "$?" -ne "0" ] ; then
                    echo "   >> Error to apply format"
                fi
            else
                echo "Cannot find "$gitdir/$fl" ($extfl)"
            fi
        fi
    done
}

And I also use that in pre-commit hook (use it at your own risk!):

#!/bin/bash

gitdir=`git rev-parse --show-toplevel`
if [ "$?" -ne "0" ] ; then
    echo "Cannot get git root dir"
    exit 1 
fi

haserror=false

echo "Format ($gitdir):"
allfiles=`git diff --name-only`
for fl in $allfiles ; do
    extfl="${fl##*.}"
    if [ "$extfl" == "hpp"  ] || [ "$extfl" == "h"  ] || [ "$extfl" == "cpp"  ]  || [ "$extfl" == "c"  ]; then
        if [ -f "$gitdir/$fl" ] ; then
            echo "Format "$gitdir/$fl" ($extfl)"
            clang-format -i "$gitdir/$fl"
            git add "$gitdir/$fl"
            if [ "$?" -ne "0" ] ; then
                echo "   >> Error to apply format"
                haserror=true
            fi
        else
            echo "Cannot find "$gitdir/$fl" ($extfl)"
            haserror=true
        fi
    fi
done

echo "Format ($gitdir):"
allfiles=`git diff --name-only --cached`
for fl in $allfiles ; do
    extfl="${fl##*.}"
    if [ "$extfl" == "hpp"  ] || [ "$extfl" == "h"  ] || [ "$extfl" == "cpp"  ]  || [ "$extfl" == "c"  ]; then
        if [ -f "$gitdir/$fl" ] ; then
            echo "Format "$gitdir/$fl" ($extfl)"
            clang-format -i "$gitdir/$fl"
            git add "$gitdir/$fl"
            if [ "$?" -ne "0" ] ; then
                echo "   >> Error to apply format"
                haserror=true
            fi
        else
            echo "Cannot find "$gitdir/$fl" ($extfl)"
            haserror=true
        fi
    fi
done


if [[ $haserror == true ]] ; then
    echo "Failed..."
    exit 1
fi

Do not forget to name this script: “.git/hooks/pre-commit”
And make it executable: “chmod +x .git/hooks/pre-commit”