bash - 在 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
解决方案
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";
推荐阅读
- swift - 带有 Swift 5.5 的 Xcode 13.0 将不再使用“import CreateML”语句构建我的项目,如何解决?
- python - pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]登录超时已过期 (0) (SQLDriverConnect)')
- sql - 如果在 SQL Server 中没有要选择的值,则选择值 = 0
- c# - 如何在 C# 中进行多行输入?
- kotlin - 从 ViewModel 启用/禁用登录按钮
- excel - 从工作簿中的一张工作表复制并复制到另一个目录中的另一本关闭的书
- flutter - Flutter如何将表单数据传递给api
- python-3.x - 是否有可能将标签拖到 tkinter 中同一父标签中的另一个位置?
- flutter - 如何替换 Flutter 中捆绑的 Dart SDK 以在 Apple Silicon (ARM64) 上原生运行?
- javascript - 为什么本机 javascript 函数 sort() 中的第一项 - 在我的数组中是第二项?