3 ms·
Ideally you avoid the need for escaping at all. That's easy to do as long as you have access to the execve family of routines, avoid eval inside the shell scrip
by wahern 9y ago
Ideally you avoid the need for escaping at all. That's easy to do as long as you have access to the execve family of routines, avoid eval inside the shell script, and don't need to parse strings from external sources. If the shell variable $V contains a string with metacharacters, then
X="$V"
/bin/foo "$V"
is perfectly safe.[1]
That's very much like the proper approach to preventing SQL injection exploits--focus on using parameterized interfaces rather than figuring out where, how, and which metacharacters to escape. And it's consistent with the rule for secure programming more generally, which is to avoid mixing code and data.
[1] You still usually want to quote variables when passing them, but that's to avoid field splitting and pathname expansion, not because you're at risk of an argument accidentally being evaluated as code. Section 2.1 Shell Introduction and section 2.6 Word Expansions of the Shell Command Language volume of POSIX explain this concisely. Even if you only ever program in Bash, having the POSIX standard handy is immensely useful because it explains these things in a more concise and structured manner than Bash's manual page.
I usually stick to POSIX constructs in my shell scripts because it's just easier to be confident about their correctness. If I find myself pining for a Bash-ism that's a strong hint I should be using a more powerful language family altogether. Nonetheless, Bash adheres to the mechanics of word expansion as described by POSIX. The biggest deviation is pathname expansion, which is easily avoided.