1

I have been using the trap function for a while now, but am running into an issue I don't understand.

Here is a reprex:

err_report() {
    
    echo -e "ERROR LINE $1"
    exit 1;
}
trap 'err_report ${LINENO}' ERR

existing=$(echo test | grep -oP "x")

This will throw an error because the result of the grep is empty. When I run the code without the trap, all works fine. I tried setting set +u but that didn't help..

What am I doing wrong here?

Thanks

pieterjanvc
  • 273
  • 2
  • 7

1 Answers1

4

When grep fails to match anything, it'll exit with a non-zero exit status, triggering the ERR trap. Since you're not interested in grep's exit status here, this should do the trick:

existing=$(echo test | grep -oP 'x' || true)
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108