You wrote:
differenceCode=$git diff HEAD^ HEAD --exit-code -- ./package.json
in your script. (Why did you put a dollar sign $ in front of git?)
This is the immediate source of your problem. $git is an unset variable; in sh, unset variables expand to nothing; so you are running the command:
diff HEAD^ HEAD --exit-code -- ./package.json
and not the command:
git diff HEAD^ HEAD --exit-code -- ./package.json
If you remove the stray $ sign, that problem will go away.
Your subsequent:
echo "test - $?"
will show the exit code from the command you ran, if it gets executed. The fact that it doesn't get executed indicates that the line:
. "$(dirname "$0")/_/husky.sh"
must have set the -e option ("exit on error"). If it did that, you don't need a subsequent test. But there is another error here:
echo "test - $?"
if [ "$?" != 0 ]; then
npm install
fi
You would need to remove the echo command, because echo itself is a command, and as such, it sets the $? last-command exit status variable. So if echo succeeds—it almost always does—it will set $? to zero.
If -e is set, as it appears to be, we won't get this far if $? is not zero. Since -e is set, it's important not to allow the git diff command to cause the script to exit early. To fix that, replace the whole sequence with:
if git diff HEAD^ HEAD --exit-code -- ./package.json; then
# ... code to handle a zero exit code here
else
# ... code to handle a nonzero exit here
fi
The test will now work even with -e set.
You can simplify this a bit since you have nothing to do in the then section by writing:
if ! git diff HEAD^ HEAD --exit-code -- ./package.json; then
npm install
fi
and once you do that, you can simplify this one more step by writing:
git diff HEAD^ HEAD --exit-code -- ./package.json || npm install
but the main things to do are:
- remove the
$;
- move the
git diff command into the if test.
These are what's required; everything else is optional.