Stop fighting with nested quoting in your shell variables

Shell Scripting / Bash Tricks

Stop fighting with nested quoting in your shell variables

🧩 The Challenge

Trying to pass a complex string containing both single and double quotes into a function or a command always ends in a headache. I’ve wasted entire afternoons escaping slashes just to get a simple argument to pass through correctly.

💡 The Fix

Use the printf %q format specifier to wrap your variables in a format the shell can safely execute later. It turns messy, unpredictable strings into clean, quoted shell-safe arguments automatically.

safe_var=$(printf "%q" "$dirty_variable")
eval "my_command --data $safe_var"

⚙️ Why It Works

This works because printf %q escapes all non-alphanumeric characters by adding backslashes, effectively turning any arbitrary string into a literal that the shell interpreter won’t accidentally mangle or expand.

🚀 Pro-Tip: Never use eval if you can possibly avoid it, but when you have to, printf %q is the only thing standing between you and a massive security hole.

Linux Tips & Tricks | © ngelinux.com | 8/25/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted