PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

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

 October 28, 2022     bash, bash-trap, is-empty     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing