GitHub Action: bash script grep match failing but works locally

Viewed 841

I am writing a GitHub Action. When testing it, I am having a lot of trouble to get a simple bash script to work.

The bash script is meant to test that the Java version installed on the machine matches a regular expression. The regular expression is an argument to the bash script ($1), as you can see in the workflow descriptor.

I forked the setup-java action which had this script, and the test passes there.

Relevant snippets

GitHub workflow

Full file

    - name: Verify Java 8
      if: runner.os != 'windows'
      run: __tests__/verify-java.sh "Zulu.*1\.8\.0_265" "${{ steps.setup-java-sdkman.outputs.path }}" "${{ steps.setup-java-sdkman.outputs.version }}"

Bash script

Full file

java_version="$(java -version 2>&1)"
echo "Found java version: $java_version"
echo "Grepping for '$1'"
if [ -z "$(echo $java_version | grep "$1")" ]; then
  echo "::error::Unexpected version"
  exit 1
fi

Current failure

GH Action Log

Run __tests__/verify-java.sh "Zulu.*1\.8\.0_265" "/opt/hostedtoolcache/java-8.0.265-zulu/1.0.0/x64" "8.0.265-zulu"
Found java version: openjdk version "1.8.0_265"
OpenJDK Runtime Environment (Zulu 8.48.0.53-CA-linux64) (build 1.8.0_265-b11)
OpenJDK 64-Bit Server VM (Zulu 8.48.0.53-CA-linux64) (build 25.265-b11, mixed mode)
Grepping for 'Zulu.*1\.8\.0_265'
Error: Unexpected version
Error: Process completed with exit code 1.

I've spent hours on this simple issue. When I run the script locally on a Mac, it works... I even started an online Linux shell to try it on Ubuntu, and it also works... so I have no idea why it fails only on GitHub Actions!

Any help would be appreciated.

1 Answers

Elaboration on the @smootherbug comment:

grep returns with an exit code 1, if there is no match. GitHub Actions stops executing a script if any command returns a non-zero exit code.

To uderstand grep behavior, try this in your coommand line (linux bash):

$ echo "a" | grep b
$ echo $?
1

how to bypass this?

java_version="$(java -version 2>&1)"
echo "Found java version: $java_version"
echo "Grepping for '$1'"
echo "$java_version" | grep -q "$1" || echo "::error::Unexpected version" && exit 1
Related