bash脚本 - 无法在值中使用双引号设置变量 [英] bash script - unable to set variable with double quotes in value

查看:354
本文介绍了bash脚本 - 无法在值中使用双引号设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要帮助来修复这个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 = $(其中mongo);

exp =db.profile_versions_20170420.find({account:$ {_ account},profile:$ {_ profile},version:$ {_ version}})。pretty();;
$ {_ mongo} $ {host} / $ {db} --eval$ exp

set + x

输出显示:

  + host = 127.0.0.1 
+ db = mydev
+ _account = foo
+ _profile = bar
+ _version = 201704112004
++其中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版本:3.2.4
连接to:127.0.0.1/mydev
2017-04-22T15:32:55.012-0700 E QUERY [thread1] ReferenceError:foo未定义:
@(shell eval):1:36

我需要的是帐户:foo profile:bar用双引号括起来。

解决方案

在bash(和其他POSIX shell)中,以下2个状态是等价的:

  _account = foo 
_account =foo

您想要做的是保留报价,因此您可以执行以下操作:

  _account = ''foo''


Need help in fixing this bash script to set a variable with a value including double quotes. Somehow I am defining this incorrectly as my values foo and bar are not enclosed in double quotes as needed.

My script thus far:

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

Output shows:

+ 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

What i need is account:"foo", profile:"bar" to be enclosed in double quotes.

解决方案

In bash (and other POSIX shells), the following 2 states are equivalent:

_account=foo
_account="foo"

What you want to do is to preserve the quotations, therefore you can do the following:

_account='"foo"'

这篇关于bash脚本 - 无法在值中使用双引号设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆