Skip to content

Clear terminal screen/console in Golang

homepage-banner

Introduction

When working with a console or terminal-based applications, you may find a need to clear the screen to improve readability and user experience. In Golang, there are different methods to clear the screen and create a clean slate for the next output. This post will discuss three ways of achieving this in Golang.

Use exec

package main

import (
    "os"
    "os/exec"
)

func main(){
    fmt.println("hello world")
    cmd := exec.Comand("clear")
    cmd.Stdout = os.Stdout
    cmd.Run()
}

Use ANSI

fmt.Printf("\x1bc")
// from bottom

// OR

fmt.Printf("\x1b[2J")
// from top

Reference

  • https://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Leave your message