9

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!

1 Answer 1

8

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'
>
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thanks, I suspected something as simple as this should exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.