bash script - unable to set variable with double quotes in value bash script - unable to set variable with double quotes in value unix unix

bash script - unable to set variable with double quotes in value


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"'


Since part of what you're doing here is forming JSON, consider using jq -- which will guarantee that it's well-formed, no matter what the values are.

host='127.0.0.1'db='mydev'_account="foo"_profile="bar"_version=$1json=$(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"

This makes jq responsible for adding literal quotes where appropriate, and will avoid attempted injection attacks (for instance, via a version passed in $1 containing something like 1, "other_argument": "malicious_value"), by replacing any literal " in a string with \"; a literal newline with \n, etc -- or, with the | tonumber conversion, failing outright with any non-numeric value.


Note that some of the syntax above requires jq 1.5 -- if you have 1.4 or prior, you'll want to write {account: $account, profile: $profile} instead of being able to write {$account, $profile} with the key names inferred from the variable names.


When you need to use double quotes inside a double quoted string, escape them with backslashes:

$ foo="acount:\"foo\"" sh -c 'echo $foo'  acount:"foo"