@@ 0,0 1,62 @@
+package main
+
+import (
+ "bufio"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+)
+
+func main() {
+ var verbose, silent bool
+ var linecount int
+ flag.BoolVar(&verbose, "v", false, "always print file headers")
+ flag.BoolVar(&silent, "q", false, "never print file headers")
+ flag.IntVar(&linecount, "n", 10, "print the last `NUM` lines")
+ flag.Parse()
+
+ if linecount == 0 {
+ os.Exit(0)
+ }
+
+ doTail := func(r io.Reader) {
+ lineBuffer := make([]string, linecount)
+ var lc, iIdx int
+ scanner := bufio.NewScanner(r)
+ for scanner.Scan() {
+ lineBuffer[iIdx] = scanner.Text()
+ iIdx++
+ lc++
+
+ if iIdx == linecount {
+ iIdx = 0
+ }
+ }
+
+ for lrem := min(lc, linecount); lrem > 0; lrem-- {
+ i := iIdx - lrem
+ if i < 0 {
+ i += linecount
+ }
+ fmt.Println(lineBuffer[i])
+ }
+ }
+
+ if flag.NArg() > 0 {
+ for _, fname := range flag.Args() {
+ if verbose || (!silent && flag.NArg() > 1) {
+ fmt.Printf("==> %s <==\n", fname)
+ }
+ ifile, ierr := os.Open(fname)
+ if ierr != nil {
+ fmt.Fprintln(os.Stderr, ierr.Error())
+ os.Exit(1)
+ }
+ doTail(ifile)
+ ifile.Close()
+ }
+ } else {
+ doTail(os.Stdin)
+ }
+}