Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a tail script without the tail command

Tags:

bash

unix

How would you achieve this in bash. It's a question I got asked in an interview and I could think of answers in high level languages but not in shell.

As I understand it, the real implementation of tail seeks to the end of the file and then reads backwards.

like image 949
t0mmyt Avatar asked Nov 29 '22 08:11

t0mmyt


1 Answers

The main idea is to keep a fixed-size buffer and to remember the last lines. Here's a quick way to do a tail using the shell:

#!/bin/bash

SIZE=5
idx=0

while read line
do
    arr[$idx]=$line
    idx=$(( ( idx + 1 ) % SIZE )) 
done < text

for ((i=0; i<SIZE; i++))
do
    echo ${arr[$idx]}
    idx=$(( ( idx + 1 ) % SIZE )) 
done
like image 138
cnicutar Avatar answered Dec 06 '22 09:12

cnicutar