简体   繁体   English

Bash和MongoDB:Eval中的空白不起作用

[英]Bash and MongoDB: Whitespaces in Eval not working

In a bash script, this won't work with Unexpected token ILLEGAL 在bash脚本中,这不适用于Unexpected token ILLEGAL

#!/bin/bash
value="White Spaced String"
mongo --verbose localhost:27017/myDB --eval 'db.ips.update({"id":"id"}, { $push: { "key": {"key":"'$value'"}}})'

where as this works: 这在哪里工作:

#!/bin/bash
value="NonWhiteSpacedString"
mongo --verbose localhost:27017/myDB --eval 'db.ips.update({"id":"id"}, { $push: { "key": {"key":"'$value'"}}})'

Any ideas ow to work around this? 有什么想法可以解决这个问题吗? I tried: 我试过了:

value="${value// /\\\\ }" which will substitute whitespaces with \\ escape signs and a whitespace. value="${value// /\\\\ }" ,它将用\\逃逸符号和空白替换空白。 Yet, no success. 然而,没有成功。

This does work, yet I want to preserve the whitespaces in my JSON in Mongo: 确实可以,但是我想在Mongo中的JSON中保留空格:

value="${value// /_}"

The argument to the --eval option needs to be a single bash word, so you need to avoid bash word-expanding $value . --eval选项的参数必须是单个bash单词,因此您需要避免bash单词扩展$value That means you need to put the expansion inside double-quotes: 这意味着您需要将扩展​​名放在双引号中:

mongo --verbose localhost:27017/myDB --eval \
  'db.ips.update({"id":"id"}, { $push: { "key": {"key":"'"$value"'"}}})'
                                                         ^      ^

That argument consists of a single-quoted segment, a double-quoted segment, and then a final single-quoted segment. 该参数由一个单引号段,一个双引号段和最后一个单引号段组成。 The double quotes inside the single-quoted segments are, of course, ordinary characters. 当然,单引号中的双引号是普通字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM