Here's a robust Bash function that, despite using eval , should be safe.
All references to ${varName} variables in the input text are extended based on the variables of the calling shell.
Nothing else is revealed: neither references to variables whose names are not enclosed in {...} (for example, $varName ), nor command substitutions ( $(...) and the outdated `...` syntax), nor arithmetic substitutions ( $((...)) and the deprecated syntax $[...] ).
To treat a $ as a literal, \ -escape it; eg:. \${HOME}
Please note that input is only accepted through stdin.
Example:
$ expandVarsStrict <<<'$HOME is "${HOME}"; `date` and \$(ls)'
Function Source Code:
expandVarsStrict(){ local line lineEscaped while IFS= read -r line || [[ -n $line ]]; do
The function assumes that there are control characters 0x1 , 0x2 , 0x3 and 0x4 in the input element, because these characters. used internally - since the function processes the text, this should be a safe guess.
mklement0 Oct 21 '16 at 3:31 on 2016-10-21 03:31
source share