将 shell 变量传递给 mongodb 脚本

Pass shell variable to mongodb script

我在 centos 7 服务器上使用 jenkins 和 mongodb。 我想将一些 jenkins 构建成功数据插入到我的 mongo 数据库中。 这是我 post 构建任务 shell:

中的代码
echo 'password' | su -

mongo jenkinsdb <<\EOF
db.history.insert({wokspace:$WORKSPACE,remote_url:$GIT_URL,branch:$GIT_BRANCH,type:"back",date:$(date 
'+%Y-%m-%d %H:%M:%S'),description:$short_description})


db.history.find()
EOF

问题是 mongo 将 Jenkins 环境变量解释为简单字符串。 我如何将这些变量传递给 mongo 脚本?

您正在通过在 EOF 之前使用 \ 来防止变量插值。见 https://tldp.org/LDP/abs/html/here-docs.html:

Quoting or escaping the "limit string" at the head of a here document disables parameter substitution within its body. The reason for this is that quoting/escaping the limit string effectively escapes the $, `, and \ special characters, and causes them to be interpreted literally.

serene% a=1

serene% cat <<T
heredoc> $a
heredoc> T
1

serene% cat <<\T
heredoc> $a
heredoc> T
$a

如果您希望进行插值,请删除反斜杠。