How can I erase the scroll-back in a terminal using Go?
In OS X using Terminal, I can run:
$ print '\e[3J'
and it will "Erase the scroll-back (aka 'Saved Lines')." Great!
But, in Go, when I run:
exec.Command("print", `\e[3J`).CombinedOutput()
I get the error that exec: "print": executable file not found in $PATH
, which makes sense:
$ type -a print
print is a shell builtin
The helpful Gophers in Slack mentioned I should look into communicating the the terminal app directly (whether it be Terminal, iTerm, iTerm2, etc.). However, I'm at a loss even after looking at this: https://www.iterm2.com/documentation-scripting.html
fmt.Printf(string([]byte{0x1b,'[', '3', 'J'}))
should suffice. But you really should use a terminal library, which knows which codes to use depending on the terminal emulator in use.
Something like termbox-go.
For the usually available codes and their byte values, you can try xterm-docu but your mileage may vary, as you use different terminal emulators.
print
is a shell builtin, so it cannot be executed from go. You could use the /bin/echo
binary, /usr/bin/clear
, or just fmt.Println
the escape sequence:
seq := "\x1b\x5b\x48"
// option 1
out, _ := exec.Command("/bin/echo", seq).Output()
fmt.Println(string(out))
// option 2
out, _ := exec.Command("/usr/bin/clear").Output()
fmt.Println(string(out))
// option 3 (prefered)
fmt.Println(seq)