如何通过unix命令的shell脚本比较输出中的任何字符串

Sid*_*ari 4 command-line bash scripts

我一运行一个命令就会得到一个日志文件(进程仍在后台运行)。现在我想从该日志文件中获取状态(干净或不干净)。如果状态是干净的,那么我将保留该进程,如果它不干净,那么我必须终止由我的第一个命令启动的进程,并再次重新运行相同的命令。

我已经尝试过cat logfilename | grep "un-clean"。但我不知道如何在 shell 脚本中验证这个输出。

我想要类似的东西(大致)var= clean then the output of above command == var if yes then echo "ok" else re-run command

我已经尝试了一些命令,但对我不起作用。

Ser*_*nyy 6

基本上,你想要这个结构

if grep -q "un-clean"  /path/to/log_file.log ;
then
    # put some command in case we find result is unclean
else 
    # if the output is ok, do something else
fi
Run Code Online (Sandbox Code Playgroud)

它所做的只是默默地(不打印到屏幕)检查文件中是否存在字符串“unclean”的匹配项。如果有,我们执行 if 部分,否则 - 我们执行 else 部分。

这是一个例子:

$> if grep -q 'root' /etc/passwd ; then  echo "This user exists" ; else echo "This user doesn't exist"; fi    
This user exists
$> if grep -q 'NOEXIST' /etc/passwd ; then  echo "This user exists" ; else echo "This user doesn't exist"; fi 
This user doesn't exist
Run Code Online (Sandbox Code Playgroud)

还可以做的是从脚本启动您想要的命令,但在后台。这样我们就可以得到它的PID。这就是我的意思

$> echo "HelloWorld"   &                                                                                      
[1] 6876
Run Code Online (Sandbox Code Playgroud)

添加&原因echo "HelloWorld"在后台运行,我们将其 PID 存储在$!变量中。因此,我们可以做类似的事情,

some-command  &
CMD_PID=$!
if grep -q "un-clean"  /path/to/log_file.log ;
then
         kill -TERM $CMD_PID
else 
        # if the output is ok, do something else
fi
Run Code Online (Sandbox Code Playgroud)