Notes & TILs
Search…
Clearing terminal screen in Go
There are two ways I like (without any external dependency)

Using os/exec package

I have added some boilerplate code to make sure you see whats happening. I think this is probably the best way to do this.
1
package main
2
3
import (
4
"os"
5
"fmt"
6
"os/exec"
7
"time"
8
)
9
10
func main() {
11
fmt.Println("this is a line")
12
fmt.Println("this is a line")
13
fmt.Println("this is a line")
14
fmt.Println("this is a line")
15
fmt.Println("this is a line")
16
​
17
fmt.Println("Clearing Screen in 2s...")
18
​
19
// sleep for 2 seconds
20
duration, _ := time.ParseDuration("2s")
21
time.Sleep(duration)
22
23
c := exec.Command("clear")
24
c.Stdout = os.Stdout
25
c.Run()
26
}
Copied!

Using ANSI Escape Sequences

Not a good way but may come in handy for some situations.
1
package main
2
3
import (
4
"fmt"
5
"time"
6
)
7
8
func main() {
9
fmt.Println("this is a line")
10
fmt.Println("this is a line")
11
fmt.Println("this is a line")
12
fmt.Println("this is a line")
13
fmt.Println("this is a line")
14
​
15
fmt.Println("Clearing Screen in 1s...")
16
dur, _ := time.ParseDuration("1s")
17
time.Sleep(dur)
18
​
19
fmt.Print("\033[2J")
20
}
Copied!
The sequence \033[2J is read as Esc[2J where "2j" clears the screen and moves the cursor to the home position (line 0, column 0).
Last modified 1mo ago