Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use result from mongodb in shell script

I am trying to use the result printed from a parameterized MongoDB script file in a bash script.

The call looks like this:

mongo --quiet server/db --eval "a='b'" mongoscript.js

Inside mongoscript.js there is a print statement that prints the value 'foo' I want to use in my shell script. The problem is that when I execute above statement I get:

b
foo

instead of just 'foo'

Thus, if I do

res=`mongo --quiet server/db --eval "a='b'" mongoscript.js`

res contains both lines.

I can of course solve this with

res=`mongo ... |tail -n 1`

but I am hoping there is a more general way to avoid this superfluous output.

Thanks!

like image 633
Nodebody Avatar asked Feb 04 '14 13:02

Nodebody


1 Answers

The superfluous output is the result of your assignment of a='b', which displays the result of the assignment in this context.

If you add the var keyword for variable assignment, you shouldn't have any extra output (and can still use the variable a in your script):

$ mongo --quiet --eval "var a='b'" mongoscript.js
foo

You can see the same behaviour in the mongo shell:

> a='b'
b
> var a='b'
>
like image 186
Stennie Avatar answered Oct 03 '22 04:10

Stennie