在作为另一个命令一部分的 heredoc 中解析变量

Resolving variables in a heredoc that is part of another command

我试图让 "user" 和 "pw" 变量在用单引号引起来的 heredoc 中解析,因为它是更大命令的一部分。我相信正如这里所描述的 Using variables inside a bash heredoc 问题是由于整个命令包括 "END" 部分的单引号引起的,但我没有看到将整个命令用引号引起来的替代方法,因为 heredoc 被传递给 mongo shell 作为 kubernetes 中的单个参数。代码如下:

#!/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

在变量赋值的字符串两边加上双引号,这样变量就会在里面展开。

doc="mongo <<END
use DATABASE
db.auth('$user', '$pw')
db.collection.find()
END
"