Course contentsShow
← Linux
Lesson 136 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Safe Variable Expansion Quoting

Neutralize shell injection risks by applying rigorous quoting standards.

In this lesson, you will learn how to wrap your variables in double quotes to prevent the shell from misinterpreting their contents, effectively neutralizing the risk of shell injection.

When you use a variable in Bash, the shell performs "word splitting" and "pathname expansion" on the result. If a variable contains spaces or special characters (like * or ?), the shell might treat them as multiple arguments or commands instead of a single string. This behavior is a common vector for shell injection, where an attacker—or even just a filename with an unexpected character—causes your script to behave unpredictably.

To stay safe, you must treat your variables as literal units by surrounding them with double quotes (").

Why Quoting Matters

Consider a script designed to delete a temporary file provided by a user:

filename=$1
rm $filename

If a user provides a filename like my file.txt, the shell sees two distinct arguments: my and file.txt. The rm command will then try to delete two separate files instead of one. Even worse, if a user provides a filename like *; rm -rf /, an unquoted variable could lead to catastrophic unintended command execution.

The Safe Pattern

To neutralize these risks, always wrap your variable expansions in double quotes:

filename=$1
rm "$filename"

By adding those quotes, you tell the shell: "Treat everything inside this variable as one single string, regardless of what characters it contains." The shell will no longer attempt to split the contents on spaces, nor will it attempt to interpret special characters as wildcards or command operators.

This rule applies everywhere: when passing variables to functions, using them in if statements, or echoing them to logs. It is a fundamental defensive practice that ensures your script only performs the exact operation you intended, shielding your logic from the messy realities of external input.

Key Takeaway: Always wrap your variable expansions in double quotes to force the shell to treat the contents as a single, literal unit, effectively preventing accidental word splitting and malicious injection.