BASH If [[ "$a" == *"$b"* ]] 始终为真,即使不应该为真

Aar*_*son 4 linux bash shell

我正在尝试编写一个小型 bash 脚本来监视 RiotShield(英雄联盟的第 3 方玩家抓取工具)的输出是否崩溃。如果在日志中找到关键字,它应该终止该进程并重新启动它。

这是我的 bash 脚本:

#!/bin/bash
crash[1]="disconnected"
crash[2]="38290209"
while true; do
    list=$(tail log.log)
    #clear
    echo "Reading Log"
    echo "========================================"
    echo $list
    for item in ${list//\\n/ }
    do
            for index in 1 2
            do
                    c=${crash[index]}
                    #echo "Crash Word:" $c
                    if [[ "$c" == *"$item"* ]]; then
                            echo "RiotShield has crashed."
                            echo "Killing RiotShield."
                            kill $(ps aux | grep '[R]iotShield.exe' | awk '{print $2}')
                            echo "RiotShield killed!"
                            echo "Clearing log."
                            echo > log.log
                            echo "Starting RiotShield"
                            (mono RiotShield.exe >> log.log &)

                    fi
            done

    done

    sleep 10
done
Run Code Online (Sandbox Code Playgroud)

我的崩溃数组是我知道崩溃时在日志中显示的关键字。我在那里的 38290209 仅用于测试目的,因为它是我在英雄联盟中的召唤师 ID,当我搜索我的召唤师名称时,该 ID 将显示在日志中。

问题是即使断开连接并且 38290209 也不会出现在我的日志中

if [[ "$c" == *"$item"* ]]; then
Run Code Online (Sandbox Code Playgroud)

触发,终止 RiotShield 进程,然后重新启动它。

随着我找到更多崩溃关键字,崩溃数组的长度将会增加,所以我不能这样做

if [[ "$c" == "*disconnected*" ]]; then
Run Code Online (Sandbox Code Playgroud)

请并感谢 SOF

编辑:

添加工作代码:

#!/bin/bash
crash[1]="disconnected"
crash[2]="error"
while true; do
    list=$(tail log.log)
    clear
    echo "Reading Log"
    echo "========================================"
    echo $list
    for index in 1 2
    do
            c=${crash[index]}
            #echo "Crash Word:" $c
            if [[ $list == *$c* ]]; then
                    echo "RiotShield has crashed."
                    echo "Crash Flag: " $c
                    echo "Killing RiotShield."
                    kill $(ps aux | grep '[R]iotShield.exe' | awk '{print $2}')
                    echo "RiotShield killed!"
                    echo "Clearing log."
                    echo > log.log
                    echo "Starting RiotShield"
                    (mono RiotShield.exe >> log.log &)
                    fi
            done
    sleep 10
done
Run Code Online (Sandbox Code Playgroud)

dog*_*ane 5

我认为你的表达式中的操作数是错误的。它应该是:

if [[ $item == *$c* ]]; then
Run Code Online (Sandbox Code Playgroud)

$c因为您想查看 ( ) 行中是否存在关键字( $item)。

另外,我不确定为什么您需要通过这样做将行分成项目:${list//\\n/ }。您可以只匹配整行。

另请注意, 中不需要双引号[[