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
