bashis-emptybash-trap

Why is trap in bash throwing an error when empty variable is assigned


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


Solution

  • 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)