Output file lines from last to first in Bash Output file lines from last to first in Bash shell shell

Output file lines from last to first in Bash


GNU (Linux) uses the following:

tail -n 10 <logfile> | tac

tail -n 10 <logfile> prints out the last 10 lines of the log file and tac (cat spelled backwards) reverses the order.

BSD (OS X) of tail uses the -r option:

tail -r -n 10 <logfile>

For both cases, you can try the following:

if hash tac 2>/dev/null; then tail -n 10 <logfile> | tac; else tail -n 10 -r <logfile>; fi

NOTE: The GNU manual states that the BSD -r option "can only reverse files that are at most as large as its buffer, which is typically 32 KiB" and that tac is more reliable. If buffer size is a problem and you cannot use tac, you may want to consider using @ata's answer which writes the functionality in bash.


tac does what you want. It's the reverse of cat.

tail -10 logfile | tac


I ended up using tail -r, which worked on my OSX (tac doesn't)

tail -r -n10