0

The goal is to exit from the script with a non-zero exit code when committing package-lock.json with no associated changes to package.json being committed.

#!/bin/bash

# exits with 1 if there were differences and 0 means no differences
file_changed() {
  git diff --quiet --exit-code "$1"
}

# exits with 1 if no lines were selected, 0 if one or more lines selected, > 1 if error
file_staged() {
  git diff --name-only --cached | grep -q "$1"
}

# package-lock.json has changed and
#   package-lock.json in staged files and
#   package.json not in staged files?
if [[ file_changed "package-lock.json" -eq 1 &&
  file_staged "package-lock.json" -eq 0 &&
  file_staged "package.json" -eq 1 ]]
then
  echo "attempted commit of package-lock.json without changes to package.json!"
  exit 1
fi

I'm fairly certain the problem lies in my files_staged function. When testing file_staged "package-lock.json" -eq 0, I get the expected results. When testing file_staged "package.json" -eq 1, it always fails.

Simplifying the problem, I can never get this condition to trigger when package.json is not in the list of files returned by git diff --name-only --cached:

if file_staged "package.json" -eq 1; then
  echo "got here."
fi

Where am I going wrong?


EDIT

@Jesse_b pointed out that I should be using $() around my function calls so that the numerical comparison operators aren't sent as arguments to the function. The following example still doesn't give the desired result:

if [[ $(file_staged "package.json") -eq 1 ]]; then
  echo "got here."
fi
1

None of the conditions in your if construct work. Since you aren't using a test command (test, [, [[) you are simply testing the return status of your function.

Example:

$ test () { echo 0; }
$ if test -eq 1; then echo yes; fi
0
yes
$ if test -eq 10; then echo yes; fi
0
yes
$ if test -eq 100000000000; then echo yes; fi
0
yes

The -eq ... is being treated as an option to the test function, and that function is returning 0 so it's being treated as a success.

You want to use a test command:

if [[ $(file_changed "package-lock.json") -eq 1 &&
  $(file_staged "package-lock.json") -eq 0 &&
  $(file_staged "package.json") -eq 1 ]]
then
  echo "attempted commit of package-lock.json without changes to package.json!"
  exit 1
fi
  • Ah, I see. You're right. By enclosing the function call in $(), I'm preventing the -eq from being sent as arguments to the function. However, I'm encountering another problem. The file_staged() function isn't working as expected. When I run the command from the command line, I get the expected results, but not in my script. I'll update my question accordingly. – Richard Mar 2 at 5:12

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.