'Catch return code from composer validate in bash script

I'm trying to write a bash script that validates that composer.lock is up to date with composer.json before attempting to run composer install.

I have tried something like this:

if composer validate --no-check-all
  then echo "Composer validation failed..."
  exit 1;
fi

# composer install

That does exit my script on validation errors, however when validation passes I still get the following output:

./composer.json is valid
Composer validation failed...

What am I doing wrong here?

Edit: The test statement in the if block is missing a negation as correctly pointed out by Jeff Schaller. It doesn't affect the question much (since the exit code from composer validate is the same). I'm leaving the original wording as to not introduce further confusion.



Solution 1:[1]

You are trusting too much the reliability of composer exit codes.
The command

composer validate --no-check-all

is returning zero and it's correct, because the command has no real problems in its execution. Consider capturing the output in a variable and reading it.

#!/bin/bash

OUTPUT=$(composer validate --no-check-all)

if [[ "$OUTPUT" == *"is valid"* ]]; then
  echo "composer.json is valid (or whatever you want to do here)"
fi

Solution 2:[2]

The only thing I noticed was that the intention behind your if seems backwards. Your intention is to exit the script if the validation fails, indicated by the return code from composer, which is documented as:

  • 0: OK
  • 1: Generic/unknown error code
  • 2: Dependency solving error code

The if conditional construct accepts a list of test-commands and ...

if its return status is zero, the consequent-commands list is executed

So what you probably intend is to invert/negate that return code, so that you exit if you get a non-zero status from composer:

if ! composer validate --no-check-all
  then echo "Composer validation failed..."
  exit 1;
fi

# composer install

It seems in your situation that composer validate ... is returning 0 no matter whether it encountered an error or not. Perhaps you're being affected by this bug report related to brew?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 franzisk
Solution 2 Jeff Schaller