2

I am writing a Git pre-commit hook client script and I want to filter through committed files and do something with the deleted ones.

I have found that with the following I can loop over all files included in a commit with the following.

#!/bin/sh

for file in $( exec git diff-index --cached --name-only HEAD )
  do
    echo $file
done

To find deleted files I believe I can use git status --porcelain <file> since it displays the first character as D when the file is deleted.

So what I need is help crafting the syntax to check whether the first character in the output of git status --porcelain <file> is a D.

#!/bin/sh

for file in $( exec git diff-index --cached --name-only HEAD )
  do
    # This line doesn't work but it's the best I've came up with.
    if git status --porcelain $lessFile == *"D"*; then
      echo "$file was deleted"
    fi
done

Or let me know if I'm way off base here. Thanks.

TJ VanToll
  • 12,584
  • 4
  • 43
  • 45

1 Answers1

3

try

 $( exec git status --porcelain | egrep "^D" | sed -e 's/^D  //' )

it may have problem for filename with space. or better

git diff-index --cached --name-status HEAD | awk '$1 == "D" { print $2 }' | while read file
do
   echo $file
done

see also this question.

Community
  • 1
  • 1
J-16 SDiZ
  • 26,473
  • 4
  • 65
  • 84