简体   繁体   English

Grep命令的输出,并在“ if”语句中使用它,bash

[英]Grep output of command and use it in “if” statement, bash

Okay so here's another one about the StarMade server. 好的,这是有关StarMade服务器的另一篇文章。

Previously I had this script for detecting a crash, it would simply search through the logs: 以前,我有此脚本来检测崩溃,它只是在日志中进行搜索:

#!/bin/bash
cd "$(dirname "$0")"
if ( grep "[SERVER] SERVER SHUTDOWN" log.txt.0); then
sleep 7; kill -9 $(ps -aef | grep -v grep | grep 'StarMade.jar' | awk '{print $2}')
fi

It would find "[SERVER] SERVER SHUTDOWN" and kill the process after that, however this is not a waterproof method, because with different errors it could be possible that the message doesn't appear, rendering this script useless. 它会找到“ [SERVER] SERVER SHUTDOWN”并在此之后终止进程,但这不是一种防水方法,因为存在不同的错误,有可能消息没有出现,从而使该脚本无用。

So I have this tool that can send commands to the server, but returns an EOF exception when the server is in a crashed state. 因此,我有此工具可以将命令发送到服务器,但是当服务器处于崩溃状态时会返回EOF异常。 I basically want to grab the output of this command, and use it in the if-statement above, instead of the current grep command, in such a way that it would execute the commands below when the grep finds "java.io.EOFException". 我基本上是想获取此命令的输出,并在上面的if语句中使用它,而不是当前的grep命令,以便当grep找到“ java.io.EOFException”时它将执行以下命令。

I could make it write the output to a file and then grep it from there, but I wonder, isn't there a better/more efficient method to do this? 我可以让它将输出写入文件,然后从那里grep,但是我想知道,是不是有更好/更有效的方法来做到这一点?

EDIT: okay, so after a bit of searching I put together the following: 编辑:好的,所以经过一番搜索,我整理了以下内容:

if ( java -jar /home/starmade/StarMade/StarNet.jar xxxxx xxxxx /chat) 2>&1 > /dev/null |grep java.io.EOFException);

Would this be a valid if-statement? 这将是有效的if陈述吗? I need it to match "java.io.EOFException" in the output of the first command, and if it matches, to execute something with "then" (got that part working). 我需要它与第一个命令的输出中的“ java.io.EOFException”相匹配,如果匹配,就可以使用“ then”执行某些操作(使该部分正常工作)。

Not sure to solve your problem, but this line: 不确定要解决您的问题,但此行:

ps -aef | grep -v grep | grep 'StarMade.jar' | awk '{print $2}'

could be change to 可以改为

ps -aef | awk '/[S]tarMade.jar/ {print $2}'

The [S] prevents awk from finding itself. [S]可防止awk自行查找。


Or just like this to get the pid 或者就是这样获取pid

pidof StarMade.jar

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

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