0

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.

Scott Buchanan
  • 1,163
  • 1
  • 11
  • 28
  • Can you throw a `set -x` at the top of the script? That should print out each line as it is evaluated. Perhaps that will give you a hint? – omajid Sep 19 '18 at 01:25
  • Have you tried quoting $pw_param, like `"$pw_param"` when you pass it to `mycommand`? – omajid Sep 19 '18 at 01:30
  • @omajid I can't quote `$pw_param` when passing it to `mycommand` or else mycommand will receive the whole thing as a single string rather than `--vars` followed by the argument as it should. But using `set -x` is helpful. Thanks. It seems that when `$pw_param` is processed it double-quotes my string, so the call is effectively `mycommand --vars '"pw='\''foo' 'bar'\''"'`. I'm not sure why bash re-quotes my quoted string like that? – Scott Buchanan Sep 19 '18 at 01:45
  • 1
    Everytime you have a bare (unquoted) varaible, bash will perform word splitting on it: https://mywiki.wooledge.org/WordSplitting – omajid Sep 19 '18 at 22:46
  • Yes, thanks. This was marked as a dup correctly (at least for my "Level 1" question): and the linked answer includes the same link you just gave. My search-foo failed me in finding that answer originally. – Scott Buchanan Sep 20 '18 at 21:12

0 Answers0