In the course of working on a way to (safely) load assignments from configuration files, I am trying to come up with a shell function that would:
- With arbitrary string received as first argument, apply safe expansions (i.e. variable expansions,
${}
expansions...) but block any unsafe expansion (including if nested in other constructs). - Assign the result to the variable name received as second argument (the variable name can be assumed safe for the purpose of this question)
- Preferably be pure shell (Bash-specific is OK for me), but a proposal using an external command would be ok if it provides better results, does not degrade performance too much and depends on utilities normally present on the basic install of UNIX-like operating systems.
- Perform the expansion while getting rid of "first level" quotes, like the shell would do.
Here is an example (assuming function safeval
meeting the above, and already loaded in current context) :
export A=1
safeval '$A$(ls /)' B
echo "$B" # Echoes 1$(ls /)
safeval '"a""b"' C
echo "$C" # Echoes ab