bash 从控制台输出中获取最后 n 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4445215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
grab last n lines from console output
提问by Hersheezy
I want to make a shell script that will effectively grab the last n lines from sterr and stin that were outputted to the console. I have a screen session running a process that will restart it if it crashes via a hacky infinite loop:
我想制作一个 shell 脚本,它可以有效地从输出到控制台的 sterr 和 stin 中获取最后 n 行。我有一个屏幕会话运行一个进程,如果它通过一个hacky无限循环崩溃,它将重新启动它:
#!/bin/bash
#This script will be started in a screen session
counter=0
while [ $counter -lt 10 ]; do
./run_some_process;
last_output=#GRAB PREVIOUS OUTPUT FROM CONSOLE HERE AND LOG TO FILE
echo -e "$last_output" >> mylog.txt;
sleep 5; #sleep for a few seconds before restarting
done
What I need is for the 7th line of code to grab the last 10 or so lines from stderr and stdin and append them to a log file
我需要的是第 7 行代码从 stderr 和 stdin 中获取最后 10 行左右并将它们附加到日志文件中
回答by Alberto Zaccagni
./run_some_process 2>&1 | tail -10 >>logfle
tail -10
will give you last ten lines, 2>&1
redirects stderr to stdout, >>logfle
appends to logfile.
tail -10
会给你最后十行,2>&1
将标准错误重定向到标准输出,>>logfle
附加到日志文件。