I'm only lightly familiar with Bash string handling and having trouble wrapping my mind around how to safely handle string assignment and quoting at a distance.
Problem Level 1
I have a variable $pw
containing a password. For simplicity, assume it cannot include quotes, new lines or control characters, but it can contain spaces. I need to interpolate this into the value of a long parameter (e.g., --vars "pw='[password]'"
), and store that parameter and value into a variable $pw_param
for interpolation itself into a later command (e.g., mycommand $pw_param
). The reason for the two steps is that there are actually multiple different parameters to the final command that get built up.
What I have so far is the following:
pw="foo bar"
pw_param="--vars \"pw='$pw'\""
If I check the contents of $pw_param
I see it contains the following:
--vars "pw='foo bar'"
Which is exactly what I want to be passed as the parameter. If pass it explicitly as the argument, then it all works correctly and my command receives it:
mycommand --vars "pw='foo bar'"
However, if I try to use the variable instead (which as I understand it should just interpolate it directly since it's not in quotes), my command doesn't receive the correct argument. I'm not sure exactly what is going on, but it's somehow not the same as the literal call above:
mycommand $pw_param
Problem Level 2
Above I assumed the password didn't contain quotes for simplicity. In real life I can't be sure of that. Ideally I'd be escaping $pw
before interpolating it into $pw_param
. I tried using the printf
approach from this answer, but I couldn't get too far, especially since I couldn't even beat level one.