简体   繁体   English

Linux Bash脚本和Mongo

[英]Linux Bash Script And Mongo

I have a bash script to check a MongoDB database and send an email if certain conditions are met. 我有一个bash脚本来检查MongoDB数据库并在满足某些条件时发送电子邮件。

Mongo give you the --eval option to return a value. Mongo为你提供了--eval选项来返回一个值。 But instead to have something like: 但相反,有类似的东西:

ALERT=true|false ALERT = TRUE | FALSE

I have: 我有:

ALERT= MongoDB shell version: 2.6.1 ALERT = MongoDB shell版本: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" marco@test.com  < /root/watchdog/email
 fi

Can someone help me? 有人能帮我吗? What I need is to assign the js variable 'alarm' to the bash variable ALARM 我需要的是将js变量'alarm'分配给bash变量ALARM

将switch --quiet添加到命令行,例如mongo --quiet --eval your-statement ,忽略你得到的字符串。

As you have it now, you're setting alert to the actual command you want to execute. 正如您现在所拥有的那样,您正在为要执行的实际命令设置alert If you want to capture the output of your mongo command, you should use: 如果要捕获mongo命令的输出 ,则应使用:

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. 直接从命令行运行mongo命令将为您提供您将收到的文本。 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 ). 这可以通过像grep -v (删除不需要的东西)或者找到mongo的命令行选项来管理输出,这将导致它根本不输出不需要的东西(例如使用--quiet ) 。 See here for more details. 有关详细信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM