Bash

Tail Last N Lines (no `tail` shortcuts)

admin by @admin ADMIN
Jun 12, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`tail -n 20` works for any case where tail is available. The pure-bash version below is useful inside containers or rescue shells where coreutils is missing.
Bash
Raw
# Standard: just use tail. -F follows across rotations.
tail -n 50 /var/log/syslog
tail -F /var/log/nginx/access.log

# Pure-bash N-line tail using array as ring buffer (rare but handy)
tail_n() {
    local file="$1" n="${2:-10}"
    local -a ring=()
    local i=0
    while IFS= read -r line; do
        ring[i % n]="$line"
        ((i++))
    done < "$file"
    local total="$i"
    local start=$(( total > n ? i % n : 0 ))
    for ((j = 0; j < (total < n ? total : n); j++)); do
        echo "${ring[(start + j) % n]}"
    done
}

tail_n /etc/hosts 5
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.