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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your response. Would you mind including the full context in your samples. Not knowing much of anything about shell scripting I'm having difficulties putting the pieces together.
just use the 2nd one. it is full and complete
Awesome, I had copied it wrong the first time I tried it. Thanks for your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.