0

I am writing git hook and very confused by next code behavior:

#!/bin/sh

exit_code=0

git diff --cached --name-only --diff-filter=ACM | while read line; do
    echo "Do something with file: $line"
    # some stuff with exit code is equals to 0 or 1
    stuff_exit_code=$?
    exit_code=$(($exit_code + $stuff_exit_code))
done

echo $exit_code
exit $exit_code

I expect that echo $exit_code will produce total amount of files for each my stuff exit code was non-zero. But I see always 0. Where is my mistake?

Ivan Velichko
  • 6,348
  • 6
  • 44
  • 90

1 Answers1

0

It's because pipes are executed in a different process. Just replaced it for for-in loop.

#!/bin/sh

exit_code=0

for file in `git diff --cached --name-only --diff-filter=ACM`
do
    echo "Do something with file: $file"
    # some stuff with exit code is equals to 0 or 1
    stuff_exit_code=$?
    exit_code=$(($exit_code + $stuff_exit_code))
done

echo $exit_code
exit $exit_code
Ivan Velichko
  • 6,348
  • 6
  • 44
  • 90