Why Your Progress Bar Turns to Junk When You Pipe It to a File
Your progress bar redraws neatly on one line. Then you run the tool from CI or redirect it to a log, and get one enormous line containing every frame it ever drew. Your terminal only made it look as though the bar was updating in place.
The usual trick is to print a carriage return (\r, byte 0x0D), then draw over what was there before:
printf '\r10%%'; sleep 1; printf '\r50%%'; sleep 1; printf '\r100%%\n'
The file keeps every frame
A terminal treats \r as "move the cursor to column zero". A file treats it as a byte to store. Only the thing drawing the screen can move a cursor, so nothing gets overwritten on disk.
Many bars also send ESC [ K (written \x1b[K), which erases from the cursor to the end of the line. That stops a short frame leaving the tail of a longer one behind. In a file, it is three more bytes of litter per frame.
It gets confusing because different tools show the same file differently:
cat logsends the bytes back to your terminal, which replays the animation instantly, so the file looks fine.cat -v logshows what is really there, with^Mfor each carriage return and^[[Kfor each erase.wc -l logcounts newlines, so thousands of frames can count as one line.grepalso splits on newlines, so one match returns the whole animation.
A wide bar breaks even on a real terminal
Quick detour for a different bug that looks much like this one. If your bar is wider than the window, it wraps onto a second row. \r then returns to the start of that row, rather than the row where the bar began.
Each redraw leaves another row behind, and the bar marches down the screen. Keep the whole line narrower than the terminal, either by keeping it short or by asking for the width and leaving a column spare. Shrinking the window mid-run is a good way to test this.
Redirecting stdout may not touch the bar at all
Progress belongs on stderr, so that stdout carries only the results. It also means that which stream you check matters as much as whether you check:
tool > outleaves stderr on the terminal, so the bar should still animate.tool 2> logsends the bar to a file, even though stdout is still a terminal.tool 2>&1 | tee logmakes both streams a pipe, so neither is a terminal.
So test the file descriptor you are about to draw on. Checking stdout and then writing to stderr gets the first two cases wrong.
Off a terminal, print occasional whole lines
Hiding progress entirely when redirected is tempting, but then a two-hour job looks identical to a hung one. A better fallback is a plain line every so often, plus one at completion.
This version uses golang.org/x/term for the terminal check. It redraws at most every 100ms on a terminal, and logs at most every 10 seconds elsewhere. It also treats TERM=dumb as a request for no cursor tricks.
package main
import (
"fmt"
"io"
"os"
"strings"
"time"
"golang.org/x/term"
)
type Progress struct {
w io.Writer
tty bool
every time.Duration
last time.Time
}
func NewProgress(f *os.File) *Progress {
tty := term.IsTerminal(int(f.Fd())) && os.Getenv("TERM") != "dumb"
every := 10 * time.Second
if tty {
every = 100 * time.Millisecond
}
return &Progress{w: f, tty: tty, every: every}
}
// Update expects total > 0 and 0 <= done <= total.
func (p *Progress) Update(done, total int, now time.Time) {
final := done == total
if !final && now.Sub(p.last) < p.every {
return
}
p.last = now
if !p.tty {
fmt.Fprintf(p.w, "progress: %d/%d (%d%%)\n", done, total, done*100/total)
return
}
n := done * 20 / total
fmt.Fprintf(p.w, "\r[%-20s] %d/%d\x1b[K", strings.Repeat("#", n), done, total)
if final {
fmt.Fprintln(p.w)
}
}
func main() {
p := NewProgress(os.Stderr)
const total = 200
for i := 1; i <= total; i++ {
time.Sleep(20 * time.Millisecond) // pretend to work
p.Update(i, total, time.Now())
}
}
Run it with 2> log and the roughly four-second job writes two lines: the first update and the last. The log's size now depends on how long the job runs, however many items it processes.
Test the redirected path, since you rarely see it
You see the animated path every time you run the tool, but the redirected one needs a test. Passing the time into Update means this can simulate 100 seconds without sleeping:
package main
import (
"bytes"
"testing"
"time"
)
func TestPipeOutputHasNoControlBytes(t *testing.T) {
var buf bytes.Buffer
p := &Progress{w: &buf, every: 10 * time.Second}
start := time.Now()
for i := 1; i <= 100; i++ {
p.Update(i, 100, start.Add(time.Duration(i)*time.Second))
}
if bytes.ContainsAny(buf.Bytes(), "\r\x1b") {
t.Fatalf("control bytes in %q", buf.String())
}
if n := bytes.Count(buf.Bytes(), []byte("\n")); n != 11 {
t.Fatalf("got %d lines, want 11", n)
}
}
Know the example's limits before you copy it:
- It only prints when
Updateis called. If one item hangs, the log goes quiet; a separate ticker would give you a true heartbeat. - It is not safe for concurrent calls. Send updates through one goroutine or add a mutex.
- If the job fails halfway on a terminal, print a newline before the error, or the message starts on the end of the bar.
Some CI jobs and wrappers pretend to be terminals
A terminal check can tell you about the file descriptor, but not whether a person is watching. docker run -t and script provide a pseudo-terminal, so your tool will animate even if the output is being recorded.
You can use that deliberately to test the terminal path:
go build -o bar .
script -qc './bar' /dev/null | cat -v
Offer a flag such as --progress=plain if your tool runs in places where detection guesses wrong. The example leaves it out, but it is a small addition and saves people from wrapping your command in odd shell contortions.
Side note for C programmers: stdio adds a second surprise. stdout is normally line-buffered on a terminal and fully buffered on a pipe, so progress can arrive late and in lumps. Go's os.Stderr has no such buffer unless you wrap it in one.
You can clean up a log you already have
To keep only the final frame of each line, remove any line-ending carriage return, then everything up to the last remaining one. The second command removes the erase sequence:
sed -e 's/\r$//' -e 's/.*\r//' -e 's/\x1b\[K//g' log
This assumes GNU sed and a bar that redraws the whole line each time. To see every frame instead, perhaps to work out where a job stalled, use tr '\r' '\n' < log.
col -b looks like the obvious tool, and it does understand carriage returns. But it overlays characters: feed it abc, a carriage return and X, and you get Xbc. A shorter final frame can therefore keep debris from a longer one, which is a splendidly faithful reproduction of the problem you were trying to remove.