DEV Community

Cover image for Simplifying Your Terminal Experience with Go: Clearing the Screen
Muhammad Saim
Muhammad Saim

Posted on

Simplifying Your Terminal Experience with Go: Clearing the Screen

Do you ever find your terminal cluttered with too much output? Fear not! In this post, we'll explore a simple Go function that clears the terminal screen, making your coding experience cleaner and more focused.

Let's take a look at the code:

package main

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

// This function clears the terminal screen.
func ClearScreen() {
    if runtime.GOOS == "windows" {
        cmd := exec.Command("cmd", "/c", "cls")
        cmd.Stdout = os.Stdout
        cmd.Run()
    } else {
        cmd := exec.Command("clear")
        cmd.Stdout = os.Stdout
        cmd.Run()
    }
}

func main() {
    // Call the ClearScreen function to clear the terminal screen.
    ClearScreen()
}
Enter fullscreen mode Exit fullscreen mode

Function Overview

The ClearScreen function is designed to clear the terminal screen, providing a clean slate for your next commands or output. Here's how it works:

  1. Checking the Operating System: First, the function checks the operating system using runtime.GOOS. On Windows systems, it uses the cls command to clear the screen, while on other systems, it uses the clear command.

  2. Executing the Command: The function then creates an exec.Command with the appropriate command to clear the screen. It sets the standard output to the terminal and executes the command using cmd.Run().

Simplify Your Terminal Experience

By integrating this function into your Go programs, you can easily clear the terminal screen whenever needed, keeping your workspace tidy and focused. Whether you're debugging code, running tests, or just exploring, a clean terminal screen can enhance your productivity and clarity.

Feel free to use and adapt this function in your own Go projects to streamline your terminal experience!

Top comments (1)

Collapse
 
ccoveille profile image
Christophe Colombier

Please accept my code review

package main

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

// This function clears the terminal screen.
func ClearScreen() {

    args := []string{"clear"}
    if runtime.GOOS == "windows" {
        args = []string{"cmd", "/c", "cls"}
    }

     cmd := exec.Command(args...)
     if cmd.Err != nil {
        // do something, like a fmt.Print
        return
     }

     cmd.Stdout = os.Stdout
     err :=  cmd.Run()
     if err != nil {
        // do something, like a fmt.Print
        return
     }
}

func main() {
    // Call the ClearScreen function to clear the terminal screen.
    ClearScreen()
}
Enter fullscreen mode Exit fullscreen mode