63

Are there any standard method in Golang to clear the terminal screen when I run a GO script? or I have to use some other libraries?

Anish Shah
  • 7,669
  • 8
  • 29
  • 40

9 Answers9

74

Note: Running a command to clear the screen is not a secure way. Check the other answers here as well.


You have to define a clear method for every different OS, like this. When the user's os is unsupported it panics

package main

import (
    "fmt"
    "os"
    "os/exec"
    "runtime"
    "time"
)

var clear map[string]func() //create a map for storing clear funcs

func init() {
    clear = make(map[string]func()) //Initialize it
    clear["linux"] = func() { 
        cmd := exec.Command("clear") //Linux example, its tested
        cmd.Stdout = os.Stdout
        cmd.Run()
    }
    clear["windows"] = func() {
        cmd := exec.Command("cmd", "/c", "cls") //Windows example, its tested 
        cmd.Stdout = os.Stdout
        cmd.Run()
    }
}

func CallClear() {
    value, ok := clear[runtime.GOOS] //runtime.GOOS -> linux, windows, darwin etc.
    if ok { //if we defined a clear func for that platform:
        value()  //we execute it
    } else { //unsupported platform
        panic("Your platform is unsupported! I can't clear terminal screen :(")
    }
}

func main() {
    fmt.Println("I will clean the screen in 2 seconds!")
    time.Sleep(2 * time.Second)
    CallClear()
    fmt.Println("I'm alone...")
}

(the command execution is from @merosss' answer)

Inanc Gumus
  • 25,195
  • 9
  • 85
  • 101
mraron
  • 2,411
  • 18
  • 27
67

You could do it with ANSI escape codes:

fmt.Print("\033[H\033[2J")

But you should know that there is no bulletproof cross-platform solution for such task. You should check platform (Windows / UNIX) and use cls / clear or escape codes.

425nesp
  • 6,936
  • 9
  • 50
  • 61
Kavu
  • 7,886
  • 3
  • 34
  • 39
18

Don't use command execution for this. It's overkill, and not guaranteed to work, and it's not secure.


I created a small cross-platform package. So it works on Windows, Linux, OS X, etc.

Install it like this:

go get github.com/inancgumus/screen

Then you can use it like so:

package main

import (
    "fmt"
    "time"
    "github.com/inancgumus/screen"
)

func main() {
    // Clears the screen
    screen.Clear()

    for {
        // Moves the cursor to the top left corner of the screen
        screen.MoveTopLeft()

        fmt.Println(time.Now())
        time.Sleep(time.Second)
    }
}
wirekang
  • 172
  • 7
Inanc Gumus
  • 25,195
  • 9
  • 85
  • 101
16

Use goterm

package main

import (
    tm "github.com/buger/goterm"
    "time"
)
func main() {
    tm.Clear() // Clear current screen
    for {
        // By moving cursor to top-left position we ensure that console output
        // will be overwritten each time, instead of adding new.
        tm.MoveCursor(1, 1)
        tm.Println("Current Time:", time.Now().Format(time.RFC1123))
        tm.Flush() // Call it every time at the end of rendering
        time.Sleep(time.Second)
    }
}
Kasinath Kottukkal
  • 2,471
  • 4
  • 22
  • 28
  • 2
    Looking at the source of goterm, it uses the same solution as [Kavu's answer](https://stackoverflow.com/a/22892171/474189). – Duncan Jones Aug 14 '19 at 05:15
  • goterm is overkill for this task (it's a full-fledged, heavy-loaded package). I suggest you to check out my answer here: https://stackoverflow.com/a/53673326/115363 – Inanc Gumus Jun 14 '20 at 17:01
10

As reported here you can use the following three lines to clear the screen:

c := exec.Command("clear")
c.Stdout = os.Stdout
c.Run()

Don't forget to import "os" and "os/exec".

merosss
  • 535
  • 6
  • 19
4

Easy solution only for nix systems (linux, unix, etc.):

fmt.Println("\033[2J")
Inanc Gumus
  • 25,195
  • 9
  • 85
  • 101
CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186
2

Here's a concise way of doing it:

package util

import (
    "os"
    "os/exec"
    "runtime"
)

func runCmd(name string, arg ...string) {
    cmd := exec.Command(name, arg...)
    cmd.Stdout = os.Stdout
    cmd.Run()
}

func ClearTerminal() {
    switch runtime.GOOS {
    case "darwin":
        runCmd("clear")
    case "linux":
        runCmd("clear")
    case "windows":
        runCmd("cmd", "/c", "cls")
    default:
        runCmd("clear")
    }
}
kyle_aoki
  • 247
  • 5
  • 6
0

For me (tested on my mobile phone in termux) this works:

os.Stdout.Write([]byte{0x1B, 0x5B, 0x33, 0x3B, 0x4A, 0x1B, 0x5B, 0x48, 0x1B, 0x5B, 0x32, 0x4A})
nTheta
  • 539
  • 3
  • 12
0

Shortest code for Windows and Linux is:

package main

import (
 "github.com/MasterDimmy/go-cls"
)
func main() {
 cls.CLS()
}
Master
  • 49
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – Nol4635 Dec 26 '22 at 03:01