10

I am trying to create a bash script for a git pre-commit hook. Whenever a commit is made, I want to check if files in a certain directory are part of the staged files and if so, run a command (Grunt task). So far I have everything working, except for only running if certain files are modified. I'm trying to get this to work:

SRC_PATTERN="site/assets/js/"
if [ grep --quiet $SRC_PATTERN `git diff --cached --name-only` ]
then
  echo "none"
  exit 0
fi

This is unfortunately giving me errors.

9

try,

git diff --cached --name-only | if grep --quiet "$SRC_PATTERN"
then
    ...

Happy hacking

4

Try it like this:

SRC_PATTERN="site/assets/js/"
if git diff --cached --name-only | grep --quiet "$SRC_PATTERN"
then
  echo "none"
  exit 0
fi

This looks a lot like the accepted answer, but that one is wrong. In bash/sh each command in a pipeline is executed in a separate subshell, so an exit in the then part will only exit the subshell, any code that follows the fi will still be executed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.