Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grab last n lines from console output

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

like image 800
Hersheezy Avatar asked Dec 14 '10 23:12

Hersheezy


People also ask

How did you find the last N lines of log file?

The tail command, as the name implies, print the last N number of data of the given input. By default it prints the last 10 lines of the specified files.

How do I get the last 50 lines of a file in Unix?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.

How do I print last 100 lines in Linux?

Show activity on this post. tail [-F | -f | -r] [-q] [-b number | -c number | -n number] [file ...] -n number : The location is number lines. -f : The -f option causes tail to not stop when end of file is reached, but rather to wait for additional data to be appended to the input.

How do I see the last 20 lines of a file in Linux?

To display last 20 lines of a file linux use the tail command. Displays the last 20 lines. The default is 10 if you leave out the -n option. Displays the last 100 bytes of the file ( without reguard for the lines).


1 Answers

 ./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.

like image 125
Alberto Zaccagni Avatar answered Sep 26 '22 01:09

Alberto Zaccagni