Quote:
Originally Posted by catkin
Unfortunately dir_path can contain arbitrary strings so using it in eval arguments would be insecure
|
The whole point of quoting a value with
printf '%q' is to make it safe for shell commands, including
eval. Any character that would, in other circumstances, cause code to be executed, gets escaped into a safe version that cannot be used to execute code. Note that of course, once you escape the string, the resulting unescaped string can no longer be considered safe for
eval.
If you ever run into as situation where
eval can be broken by a particular sequence of characters from
printf '%q', please let me know, because that would be an interesting scenario.
Another alternative is to use
declare -a to auto-parse arguments to achieve the same thing:
Code:
declare NL=$'\n'
printf -v VAL '%q' "hello${NL}there"
declare -a VAR="( ${VAL} )"
echo "VAR: [${VAR[0]}]"
> VAR: [hello
there]
Note that the double-quotes surround the parenthesis, to indicate that the whole string
"( $'hello\nthere' )" should be parsed into an array by
declare -a. And since
%q escapes characters into a single resulting escaped string, the array will only contain one item, despite the presence of any special characters within the string.
Note that you can use this technique to effectively return arrays from a function:
Code:
function get123()
{
declare -a NUMS=( '1=one' '2=two' '3=three' )
printf '%q ' "${NUMS[@]}"
}
declare -a RESULTS="( $( get123 ) )"
printf 'RESULT: [%s]\n' "${RESULTS[@]}"
> RESULT: [1=one]
> RESULT: [2=two]
> RESULT: [3=three]
It only took me fifteen years of using bash to come up with this usage.