Friday, October 28, 2022

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

Issue

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)


Answered By - Ted Lyngmo
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.