3

I need to execute a command on a remote MongoDB server, using variables declared on the shell script.

Command:

ssh [email protected] "mongo mydb --host 10.1.1.1 --port 27017 -u user -p password --authenticationDatabase admin --eval 'db.mycollection.update({}, {$push: {'"$ENTITY"': NumberInt('"$CODE"')}})' --quiet"

Note that if I use the command outside the shell script, substituting the variables, a bash -c syntax error comes up. Example:

ssh [email protected] "mongo mydb --host 10.1.1.1 --port 27017 -u user -p password --authenticationDatabase admin --eval 'db.mycollection.update({}, {$push: {foo: NumberInt(123)}})' --quiet"

bash: -c: line 0: syntax error near unexpected token `('

It's working now! Solution:

DBUPDATE="db.mycollection.update({}, {\$push: {${ENTITY}: NumberInt(${CODE})}})"

ssh [email protected] mongo mydb --host 10.1.1.1 --port 27017 -u user -p password --authenticationDatabase admin --eval "'$DBUPDATE'" --quiet
Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227

1 Answers1

1
ssh [email protected] 'mongo mydb --host 10.1.1.1 --port 27017 -u user -p password --authenticationDatabase admin --eval "db.mycollection.update({}, {$push: {'"$ENTITY"': NumberInt('"$CODE"')}})" --quiet'

I switched the double quotes with single quotes at the beginning and end and put your --eval input in double quotes.

Hunter.S.Thompson
  • 8,839
  • 7
  • 26
  • 41