grab last n lines from console output

Hersheezy picture Hersheezy · Dec 15, 2010 · Viewed 32.5k times · Source

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:

#!/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

Answer

Alberto Zaccagni picture Alberto Zaccagni · Dec 15, 2010
 ./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.