首页 > 解决方案 > 在 bash 脚本中获取文件尾部的值并存储为变量

问题描述

我无法弄清楚我做错了什么。我真正想做的是在我的 bash 脚本中运行这个命令,然后把值拿回来:

tail -1 com-html.log | grep 'Min: ,'

这在手动运行时有效:

tail -1 com-html.log | grep 'Min: ,'
Min: , MAX:

但是我无法让它在 bash 脚本中工作:(我已经简化了它,以防管道位是一个问题)

#!/bin/bash

test = $(tail -1 com-html.log)

echo "test: $test";

我究竟做错了什么?Bash 对我来说很新 - 所以请温柔=)

根据以下建议 - 我什至尝试过:

    test=$(tail -1 com-html.log | grep 'Min: ,');
    echo "test: $test"

    if [ -z "$test"]
    then
        echo "hmmm test is empty"
    fi

但它总是只显示:

hmmm test is empty

我一定错过了一些愚蠢的东西

我尝试了几种方法:

    test=$(tail -1 com-html.log | grep 'Min: ,')
    echo "test: $test";

    test=$(tail com-html.log | grep 'Min: ,')
    echo "test: $test";

甚至最简单的只是看看我是否得到任何价值:

    test=$(tail -1 com-html.log)
    echo "test: $test";

他们都有 $test 为空

更新:天哪,这就是为什么你一天不应该做太多编码的原因。你错过了愚蠢的东西!所以这个脚本会关注服务器的负载,还有内存。如果它检测到任何一个都太高,它将终止脚本并等待它在重新启动之前返回。所以我有类似的东西:

    if [ -n "$(ps -ef | grep -v grep | grep 'get-html-all-domains.cgi')" ];
    then : ;
    else
        echo "nohup perl get-html-all-domains.cgi $tld new $forks $per_page > com-html.log"
        nohup perl get-html-all-domains.cgi $tld new $forks $per_page > com-html.log &  # restart it...
    fi

现在可以了——但是当它触发时,输出到 com-html.log 不是即时的(因为它必须从数据库中获取值,然后决定没有什么可以运行)。所以为了解决这个问题,我改变了这一行:

nohup perl get-html-all-domains.cgi $tld new $forks $per_page > com-html.log &

至:

nohup perl get-html-all-domains.cgi $tld new $forks $per_page >> com-html.log &

(注意>>而不是>现在,所以它是追加而不是完全覆盖它)

然后在最后检查最后一行是否是我们正在寻找的:

    if [ -n "$(tail -2 com-html.log | grep 'Min: ,')" ]
    then
        echo "2: Seems to be at end... lets stop :)"
        echo -ne '\007'
        exit 0

    fi

标签: bash

解决方案


tail -1只显示最后一行com-html.log

因此,如果 grep 字符串 ( Min: ,) 不在最后一行,则为test空。

变量的最后一行

test=$(tail -1 com-html.log)
echo "test: $test";

任何包含Min: ,

test=$(grep 'Min: ,' < test.log)
echo "test: $test";

最后一行;如果包含Min: , 在线试用!

test=$(tail -1 com-html.log | grep 'Min: ,')
echo "test: $test";

推荐阅读