GitHub Actions: using grep when no lines selected

I filter output of commands and content of the files with grep command inside my workflow. However I have problems with grep if grep doesn’t select any lines from the input. It happens because in this case grep exits with non-zero code and forkflow fails. Workflow failure is not a desired behavior. I want to perform different actions depending on output of grep (if it is empty or not). Here is the simple example which illustrates my problem:

name: Test Grep

on: pull_request

jobs:
  testgrep:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: "grep matching pattern"
        run: |
         # Everything works fine
          echo "foo" | grep "foo"
      - name: "grep not matching pattern"
        run: |
          # Workflow failes because grep exits with 1
          echo "foo" | grep "bar"

Is there any workaround to make grep work?

1 Like

After several hours it seems I found acceptable solution. I replaced grep with sed. In example from OP I replaced echo "foo" | grep "bar" with command echo "foo" | sed -n "/bar/ p" and everything works fine.

You can use grep -c to count the number of occurences:

$ echo "foo" | grep -c "foo"
1
$ echo "foo" | grep -c "fooo"
0

This way grep doesn’t fails on exit

You can also do one of the following:

  • echo "foo" | grep "bar" || true
  • set +e
    echo "foo" | grep "bar"
    set -e
    
  • - run: |
        echo "foo" | grep "bar"
      continue-on-error: true
    
  • Perhaps use a Custom shell that doesn’t fail if a command returns a non-zero exit code (-eo pipefail removed)

Or, because the idea was to take different actions depending on whether grep found anything:

- run: |
    if echo "foo" | grep "bar"; then
        echo "do this"
    else
        echo "do that"
    fi