Home > Back-end >  Catch return code from composer validate in bash script
Catch return code from composer validate in bash script

Time:04-28

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?

CodePudding user response:

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

CodePudding user response:

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?

  • Related