1

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.

oguz ismail
  • 1
  • 16
  • 47
  • 69
shashwat
  • 7,851
  • 9
  • 57
  • 90

1 Answers1

3

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\")"
Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110