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.