Confusion about tail usage

Derek Broughton news at
Mon Feb 18 16:59:09 UTC 2008

Alexandra Zaharia wrote:

> On Feb 18, 2008 5:15 PM, stan <stanb at> wrote:
>> I am trying to write a quick shell script to delete all but the newest 3
>> files in a directory. Getting a list sorted by time, I use ls -t. I
>> figured
>> I could use tail to print all the lines in it's input file, skipping the
>> first 3 lines. I expected tail -n +3 would do this. But it does not.
> - You're trying to get a listing of the files in the current directory,
> chronologically. You're interested though to get them one on each line,
> that's why it would be better to use "ls -1t" instead of "ls -t". Notice
> how the most recent files get "on top";
> - You want to determine the newest 3 files of those: you'd need "ls -1t |
> head -n 3" ("head" for "first");
> And finally if you really want to delete each of those files (whose names
> are output by the command above), you'd need to run:
> for x in `ls -1t | tail -n $(($number_of_files-3))` ; do
>            rm -i "${x}" # rm -i for confirmation on each deletion

A tad verbose!

rm -i `ls -1t | tail -n $(($(ls -1t | wc -l)-3))`

More information about the ubuntu-users mailing list