noo*_*ber 3 unix bash shell escaping quoting
需要帮助修复此bash脚本以设置包含双引号值的变量.不知何故,我将此错误地定义为我的值,foo并且bar根据需要不用双引号括起来.
到目前为止我的脚本:
#!/usr/local/bin/bash
set -e
set -x
host='127.0.0.1'
db='mydev'
_account="foo"
_profile="bar"
_version=$1
_mongo=$(which mongo);
exp="db.profile_versions_20170420.find({account:${_account}, profile:${_profile}, version:${_version}}).pretty();";
${_mongo} ${host}/${db} --eval "$exp"
set +x
Run Code Online (Sandbox Code Playgroud)
输出显示:
+ host=127.0.0.1
+ db=mydev
+ _account=foo
+ _profile=bar
+ _version=201704112004
++ which mongo
+ _mongo=/usr/local/bin/mongo
+ exp='db.profile_versions_20170420.find({account:foo, profile:bar, version:201704112004}).pretty();'
+ /usr/local/bin/mongo 127.0.0.1/mydev --eval 'db.profile_versions_20170420.find({account:foo, profile:bar, version:201704112004}).pretty();'
MongoDB shell version: 3.2.4
connecting to: 127.0.0.1/mydev
2017-04-22T15:32:55.012-0700 E QUERY [thread1] ReferenceError: foo is not defined :
@(shell eval):1:36
Run Code Online (Sandbox Code Playgroud)
我需要的是account:"foo",profile:"bar"用双引号括起来.
由于你在这里做的部分工作是形成JSON,考虑使用jq- 这将保证它的结构良好,无论值是什么.
host='127.0.0.1'
db='mydev'
_account="foo"
_profile="bar"
_version=$1
json=$(jq -n --arg account "$_account" --arg profile "$_profile" --arg version "$_version" \
'{$account, $profile, version: $version | tonumber}')
exp="db.profile_versions_20170420.find($json).pretty();"
mongo "${host}/${db}" --eval "$exp"
Run Code Online (Sandbox Code Playgroud)
这使得jq负责在适当的地方添加文字引号,并通过替换字符串中的任何文字来避免尝试注入攻击(例如,通过$1包含类似内容的传递版本1, "other_argument": "malicious_value"); 带有等等的文字换行符- 或者,在转换时,与任何非数字值完全失败."\"\n| tonumber
请注意,上面的一些语法需要jq 1.5 - 如果您有1.4或更早版本,您将需要编写{account: $account, profile: $profile}而不是能够{$account, $profile}使用从变量名称推断的键名称进行编写.
当您需要在双引号字符串中使用双引号时,请使用反斜杠转义它们:
$ foo="acount:\"foo\"" sh -c 'echo $foo'
acount:"foo"
Run Code Online (Sandbox Code Playgroud)
在bash(和其他POSIX shell)中,以下两种状态是等效的:
_account=foo
_account="foo"
Run Code Online (Sandbox Code Playgroud)
您要做的是保留报价,因此您可以执行以下操作:
_account='"foo"'
Run Code Online (Sandbox Code Playgroud)