shashwat
shashwat

Reputation: 8004

Use variables with --eval in mongodb

I am trying to use the dynamic database name in the below bash script, but it fails with an error saying invalid escape sequence.

#!/bin/bash

...
...

db_name=test
db_existence=$(mongo mongodb+srv://$db_credentials$mongoatlas_host --eval 'db.getMongo().getDBNames().indexOf(\"$db_name\")' --quiet)

I also tried using double quotes with --eval and single quotes for DB name as in the below script, but still, it gives the same invalid escape sequence error.

db_existence=$(mongo mongodb+srv://$db_credentials$mongoatlas_host --eval "db.getMongo().getDBNames().indexOf(\'$db_name\')" --quiet)

It uses the variable name as it is if I don't use \ escape character with db_name.

I can't hardcode the DB name as my database name is coming from another command.

I think that I might be missing something very fundamental in terms of bash scripting.

Please help.

Upvotes: 1

Views: 1587

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59523

Use one of those:

--eval "db.getMongo().getDBNames().indexOf('$db_name')"

--eval 'db.getMongo().getDBNames().indexOf("'$db_name'")'

--eval "db.getMongo().getDBNames().indexOf(\"$db_name\")"

Upvotes: 3

Related Questions