在bash中停止stdout到终端

时间:2016-12-19 12:46:47

标签: bash

我有一个wee脚本来检查MySQL复制状态。但是,它会打印出用于发送到另一台服务器进行监控的API。这是脚本;

#!/bin/bash

# set up monitoring
TEST_TYPE="MySQL Replication Status"
start_date=$(date --iso-8601=seconds)
SERVER_NAME=$(hostname -f)

# Checks MySQL Replication status. Sends user(s) a notification of status
status=0
SlaveHost="localhost"
emails="admin@novarumdx.com" #multiple emails space separated
DownSubject="Replication status - Down $(hostname -f)"
GoodMessage="MySQL replication on $SlaveHost is good"

#Grab the lines for each and use awk to get the last part of the string(Yes/No)
SQLresponse=$(mysql --login-path=dbbkup hydrosense_live -e "show slave status\G" | grep -i "Slave_SQL_Running" | awk '{print $2}')
IOresponse=$(mysql --login-path=dbbkup hydrosense_live -e "show slave status\G" | grep -i "Slave_IO_Running" | awk '{print $2}')
if [ "$SQLresponse" = "No" ]; then
error="Replication on the slave MySQL server($SlaveHost) has stopped working.nSlave_SQL_Running: Non"
status=1
fi
if [ "$IOresponse" = "No" ]; then
error="Replication on the slave MySQL server($SlaveHost) has stopped working.nSlave_IO_Running: Non"
status=1
fi

# Replication status
if [ $status = 1 ]; then
for address in $emails; do
echo -e $error | mail -s "$DownSubject" $address
echo "Replication down, sent email to $address"
done
RESULT=0
else echo -e $GoodMessage
RESULT=1
fi

curl --request POST \
  --url https://ops.server.com/api/status/testruns/ \
  --user 'test:test!' \
  --header 'content-type: application/json' \
  --data "{\"server\": \"$SERVER_NAME\", \"test\": \"$TEST_TYPE\", \"start_date\": \"$start_date\", \"end_date\": \"$(date --iso-8601=seconds)\", \"result\": $RESULT}"

运行时会打印出以下内容;

MySQL replication on localhost is good
{"start_date":"2016-12-19T12:45:16Z","end_date":"2016-12-19T12:45:16Z","server":"web-3.hydrosensepro.com","test":"MySQL Replication Status","result":1,"message":""}%

第一行是好的,但我不想要其余的。如何从stdout中删除它?

2 个答案:

答案 0 :(得分:1)

我认为最好的办法是在结尾处禁用你的命令输出:

>&- 2>&- 

或者如果存在选项,则检查手动以在静音模式下运行它。然后你可以抓住转换代码来个性化输出:

if [ $? -eq 0 ]; then
    echo MySQL replication on localhost is good
else 
    echo MySQL replication on localhost is not good
fi

答案 1 :(得分:0)

你的剧本很乱。可能整个事情应该被重构,以便将人类可读的状态消息打印到标准错误,并在标准输出上输出机器可读的输出。然后你可以用

选择性地禁用其中一个
./script >/dev/null  # to see only the human-readable status messages

./script 2>/dev/null  # for the machine-readable output

这样做的方法是改变

echo "message"

echo "message" >&2

整个

(我可以考虑其他一些修复,但这应该让你开始。)