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
6
  • What does the command return? Oct 11, 2017 at 16:16
  • It returns an error from MongoDB: SyntaxError: invalid property id @(shell eval). Oct 11, 2017 at 16:39
  • What are the contents of your variables?
    – sebasth
    Oct 11, 2017 at 21:10
  • @sebasth those variables are arguments of the script (e.g. test.sh foo 123). Note that the mongo command works as intended, just not working when I use it with ssh due to the quotes. Oct 11, 2017 at 23:13
  • Put the shell commands in a script on the remote host and call that script through SSH.
    – Kusalananda
    Oct 12, 2017 at 11:12

1 Answer 1

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.

1
  • It returns the same error: SyntaxError: invalid property id @(shell eval) Oct 11, 2017 at 17:00

Not the answer you're looking for? Browse other questions tagged .