Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear the terminal screen in Go?

Tags:

go

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?

like image 595
Anish Shah Avatar asked Apr 06 '14 08:04

Anish Shah


People also ask

How do I clear the terminal page?

You can use Ctrl+L keyboard shortcut in Linux to clear the screen. It works in most terminal emulators.

How do I clear the terminal when my server is running?

If you are using the default unity terminal, you can go to Terminal > Reset and clear. then you can view it using a text editor. That would let you scroll the file manually.

How do I clear the terminal screen in CPP?

To clear the screen in Visual C++, utilize the code: system("CLS"); The standard library header file <stdlib. h> is needed.


2 Answers

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)

like image 92
mraron Avatar answered Sep 29 '22 10:09

mraron


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.

like image 38
Kavu Avatar answered Sep 29 '22 10:09

Kavu