4

I have a bash script to check a MongoDB database and send an email if certain conditions are met.

Mongo give you the --eval option to return a value. But instead to have something like:

ALERT=true|false

I have:

ALERT= MongoDB shell version: 2.6.1

 #!/bin/bash
 echo "WatchDog Jerry"

 ALERT=$(mongo ob --eval 'var now = new Date().getTime(), alert = false; db.sess.find().forEach(function(sess){ var delay = 1 * 60 * 1000; var ts = sess.ts.toNumber(); if((now - ts) > delay) alert = true;});  print(alert);')

 echo "alert: $ALERT"

 if [ "$ALERT" == "true" ]; then
     mail -s "ALARM - WatchDog Jerry" [email protected]  < /root/watchdog/email
 fi

Can someone help me? What I need is to assign the js variable 'alarm' to the bash variable ALARM

1
  • 1
    the form for assigning to variable from cmd in bash/ksh/etc is called command substitution. Do ALERT=$(mongo ...). But first, get just the mongo db --eval ... to return the info you want to see when running from the cmd line. Post separate question with mongoDB error msgs if you can't figure it out by looking at mongo doc or some googling around. Good luck. Commented Aug 20, 2014 at 3:34

2 Answers 2

6

add switch --quiet to command line, something like mongo --quiet --eval your-statement to ignore the string you got.

Sign up to request clarification or add additional context in comments.

Comments

1

As you have it now, you're setting alert to the actual command you want to execute. If you want to capture the output of your mongo command, you should use:

alert=`mongo blah blah`

or:

alert=$(mongo blah blah)

I prefer the latter form since it's easier to nest commands.

Once you've fixed that, it may still be the case that you're getting undesirable extra output from the command (as confirmed by your update).

Running your mongo command directly from the command line will give you the text you'll receive. It's then a matter of massaging that output so that the only output you see is what you want.

This can be done by piping the output through something like grep -v (to remove the unwanted stuff), or finding a command line option to mongo which will cause it not to output the unwanted stuff at all (such as using --quiet). See here for more details.

2 Comments

Thanks. I am not getting errors but the value of ALERT is "MongoDB shell version: 2.6.1" It is suppose to be true or false.
how can I return true or false from the mongo script?

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.