Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only the changed part of the file to be proccessed in pre-commit hook?

I used the following shell script in pre-commit hooks,to get only the modified lines of a cpp file which is to be commit in git. But it is giving entire file which has changed lines. How could i get only the changed lines of a file to process for pre-commit check.

Here is the script which i used:

changed_files=$(git diff-index --cached $against | \
    grep -E '[MA]   .*\.(c|cpp|cc|cxx)$' | cut -f 2)
like image 373
Aparna Elangovan Avatar asked Oct 18 '25 16:10

Aparna Elangovan


2 Answers

git diff --cached should show you the staged changes only.

I guess what you are looking for is:

git diff --cached --name-status | grep -E '[MAD] *.*\.(c|cpp|cc|cxx)$' | cut -f2

Also, you can try adding the --name-only option instead of piping the output through cut.

git diff-index --cached --name-only $against | grep -E '.*\.(c|cpp|cc|cxx)$'
like image 126
sergej Avatar answered Oct 20 '25 07:10

sergej


If said file is staged (i.e. has been git add), then you can use git diff --staged or git diff --cached (both are synonyms).

If you have more than one file staged, you can specify which one you want to look at with git diff --staged [path/filename].

like image 34
cetteSara Avatar answered Oct 20 '25 07:10

cetteSara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!