Reputation: 7739
The following code produce error "integer expression expected":
for SOURCE_PATH in work/sources/*; do
git diff --exit-code &>/dev/null || SOMETHING_TO_COMMIT=$?
if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then
echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
else
echo "COMMIT FOR $SOURCE_PATH"
git -C "$DIR/$SOURCE_PATH" commit -F ${COMMIT_MESSAGE_FILE}
fi
done
Error is on line if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then
. It seems [ "$SOMETHING_TO_COMMIT" -eq "0" ]
or [ "$SOMETHING_TO_COMMIT" -eq "" ]
should produce integer.
How to fix that ?
Upvotes: 1
Views: 1069
Reputation: 531325
Between the two current answers, there is the realization that you don't have to make a conditional assignment to SOMETHING_TO_COMMIT
. Just assign the exit status, zero or not, to the parameter; then it is guaranteed to have some non-empty integer value.
git diff --exit-code &>/dev/null; SOMETHING_TO_COMMIT=$?
if [ "$SOMETHING_TO_COMMIT" -eq 0 ]; then
echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
else
echo "COMMIT FOR $SOURCE_PATH"
git -C "$DIR/$SOURCE_PATH" commit -F ${COMMIT_MESSAGE_FILE}
fi
As Inian points out, you don't need to save the exit status if you are only going to make one comparison; you can use the git
command itself as the if
condition. Saving the value is useful when you might need to make multiple comparisons:
some_command; status=$?
if [ "$status" -eq 0 ]; then
...
elif [ "$status" -eq 1 ]; then
...
else
...
fi
Upvotes: 1
Reputation: 85683
You don't need to store the exit codes in variables at all. If the git diff
can return a non-zero exit code on failure like the most common Linux/Unix commands, you can directly use it in the if conditional as
if ! git diff --exit-code &>/dev/null ; then
echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
The !
operator asserts true of the if-condition only if the git diff
was not successful and there were no changes to commit. Also you should change your script to assert true on the if-condition and fail on the else part as
if git diff --exit-code &>/dev/null ; then
echo "COMMIT FOR ${SOURCE_PATH}"
git -C "$DIR/${SOURCE_PATH}" commit -F "${COMMIT_MESSAGE_FILE}"
else
echo "NOTHING TO COMMIT FOR ${SOURCE_PATH}";
fi
which makes it more readable and efficient.
Upvotes: 3
Reputation: 1083
The second test compares the variable with an empty string (""), but using -eq which is for integers only, so you should change it to the = operator:
if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" = "" ] ; then
Upvotes: 1