1

I am trying to get the "user" and "pw" variables to resolve in a heredoc that is wrapped with single quotes because it is part of a larger command. I believe that as described here Using variables inside a bash heredoc the issue is due to single quotes around the entire command including the "END" portion, but I am not seeing an alternative to wrapping the entire command in quotes because the heredoc is being passed to the mongo shell as a single argument in kubernetes. The code is as follows:

#!/bin/bash

user="theUser"
pw="thePW"

doc='mongo <<END
use DATABASE
db.auth("$user", "$pw")
db.collection.find()
END
'
value=$(kubectl exec -it mongo-pod -- bash -ec "$doc")

echo $value

1 Answers1

1

Put double quotes around the string in the variable assignment, so that variables will be expanded in it.

doc="mongo <<END
use DATABASE
db.auth('$user', '$pw')
db.collection.find()
END
"
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Wow, that was easier than I thought it would be. I am curious, do you have any idea why swapping the positions of the single quotes and the double quotes makes a difference? – JabberwokyStrollin Aug 22 '18 at 21:49
  • 1
    Variables are expanded inside double quotes, not inside single quotes. Once you're inside the double-quoted string, the embedded single quotes have no effect (they're sent literally to `mongo`). – Barmar Aug 22 '18 at 21:54
  • @user3389672 In general, quotes don't nest. Single-quotes don't have any special meaning inside a double-quoted string, and double-quotes don't have any special meaning inside a single-quoted string. Double-quotes in a double-quoted string must be escaped (or they'll end the string), and single-quotes *cannot* be put inside a single-quoted string. (BTW, there is at least one exception: backquotes and double-quotes mostly nest in each other. Mostly.) – Gordon Davisson Aug 22 '18 at 22:04
  • 1
    @GordonDavisson: Re: "single-quotes *cannot* be put inside a single-quoted string": This is misleading; you can write something like `'It'"'"'s fun!'`. (Technically that involves closing the single-quoted string and opening a new one, but it's important to point out, because people who aren't so familiar with Bash tend to assume that the entire word has to be a single string. The OP shows this sort of tendency in his/her question, writing e.g. `user="theUser"` instead of the normal `user=theUser`.) – ruakh Aug 23 '18 at 00:04