Skip to content
shellhacks.dev
Go

Read stdin lines

Read standard input line by line in Go with bufio.Scanner. It strips the newline, handles a last line without one, and stops with an error on very long lines.

1 min read
Summarize in AI

A Go program should read its input line by line, the way while read does in a shell.

main.goGo
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	sc := bufio.NewScanner(os.Stdin)
	n := 0
	for sc.Scan() {
		n++
		fmt.Printf("%d: [%s]\n", n, sc.Text())
	}
	if err := sc.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "read error:", err)
		os.Exit(1)
	}
}
Shell
printf 'first\n  indented line\n\nlast without newline' | go run main.go
Text
1: [first]
2: [  indented line]
3: []
4: [last without newline]

Scan advances to the next token, which is a line by default, and Text returns it without the trailing newline. Leading spaces, empty lines and a final line with no newline are all kept as they are, as the output shows. The bufio.Scanner documentation says to check Err after the loop, because Scan returns false on a read error as well as at the end of the input.

A line longer than 64 KiB makes the scanner stop with bufio.Scanner: token too long, and the loop ends without processing the rest. Raise the limit with sc.Buffer(make([]byte, 0, 64*1024), 1<<20) before the first Scan, or read with bufio.Reader.ReadString for unbounded lines.

Taggedgotext
Share

More snippets

Go

Exit with a status

Exit with a status using os.Exit(n). It ends the program at once and skips every deferred call, so cleanup in defer is not run before the exit.

1 min read
Go

Raise the scanner line limit

Raise the line limit of bufio.Scanner with Buffer(make([]byte, 0, 64*1024), max). Lines over 64 KB otherwise stop the scan with token too long.

1 min read
Go

Set a timeout for a command

Stop a command that takes too long with exec.CommandContext and context.WithTimeout. In Go 1.19 a shell's child can keep Output() waiting past the deadline.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.