grab last n lines from console output

35,991
 ./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.

Share:
35,991

Related videos on Youtube

Hersheezy
Author by

Hersheezy

Expertise includes NLP, data science, system administration, and scalable web development.

Updated on July 09, 2022

Comments

  • Hersheezy
    Hersheezy almost 2 years

    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

  • Hersheezy
    Hersheezy over 13 years
    thanks! one lil' change: ./run_some_process 2>&1 | tail -10 >>logfle Looks like stderr needed to go to stdout so it would make it to the pipe.
  • Alberto Zaccagni
    Alberto Zaccagni over 13 years
    Oh yeah sorry, my mistake ^^"