Stop bash variable expansion from breaking your regex

Shell Scripting / Bash Tricks

Stop bash variable expansion from breaking your regex

🧩 The Challenge

You finally wrote the perfect grep regex with all those backslashes and brackets, only to have your bash script treat it like a bad suggestion and garble the whole thing. I’ve spent way too many nights squinting at echo outputs trying to figure out why a single character vanished.

💡 The Fix

Use single quotes to shield your regex from the shell’s itchy trigger finger. It forces the shell to leave every single character alone so your tool actually sees the pattern you wrote.

pattern='[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
grep -E "$pattern" file.txt

⚙️ Why It Works

Single quotes create a literal vacuum where bash ignores variable expansion and escape characters entirely. When you use double quotes, bash tries to “help” by evaluating everything it sees, which is usually exactly what you don’t want when regexes are involved.

🚀 Pro-Tip: If you absolutely need a variable inside the string, close the quote, add the variable, and open a new one: ‘regex part’${VAR}’regex part’.

Linux Tips & Tricks | © ngelinux.com | 7/29/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted