2017-04-24 111 views
0

所以,我正在處理我的bash腳本中的幾個函數。我有一個工作,但我的第二個包括在雙引號""封裝的數值,從而打破我的變量替代。我已經嘗試用單個刻度圍繞這些值,但在某些情況下不起作用。bash腳本 - 函數內的變量替換和雙引號

例如:

# Functions 
unset_versions() 
{ 
    host='127.0.0.1' 
    db='mydev' 
    _account='"foo"' 
    _profile='"bar"' 
    _mongo=$(which mongo); 
    exp="db.profile_versions_20170420.update({account:${_account}, profile:${_profile}, version:${_version}},{ \$unset : { labels : true }});"; 
    ${_mongo} ${host}/${db} --eval "$exp" 
} 

然而,這是行不通的:

update_versions() 
{ 
    host='127.0.0.1' 
    db='mydev' 
    _account='"foo"' 
    _profile='"bar"' 
    _mongo=$(which mongo); 
    exp="db.profile_versions_20170420.update({account:${_account}, profile:${_profile}, version:${_version}},{ \$set : { labels : { "1" : { "name" : "data layer patch", "color" : "regal-rose" }, "2" : { "name" : "Global Functions", "color" : "melon-mambo" }}}}); 
    ${_mongo} ${host}/${db} --eval "$exp" 
} 

我知道這看起來很難看。如果有更好的方法,請提供一些建議。我也試過exp=$(....),但這似乎也沒有效果。

+1

你可能想看看這篇文章:http://stackoverflow.com/questions/6697753/difference-between-single-和雙引號在bash – codeforester

+0

這是一個很好的參考。謝謝。 – noober

回答

1

你應該逃脫「「」是這樣的:

exp="db.profile_versions_20170420.update({account:${_account},profile:${_profile}, version:${_version}},{ \$set : { labels : { \"1\" : { \"name\" : "datalayer patch\", \"color\" : \"regal-rose\" }, \"2\" : { \"name\" : "Global Functions\", \"color\" : \"melon-mambo\" }}}})";

+0

逃脫工作!謝謝 – noober