DEV Community

Michele Caci
Michele Caci

Posted on • Edited on

Clearing your Unix Terminal and other commands using Go scripts

When you want to run shell commands, like for example clearing the terminal, from a Go program or script this is how you can do:

cmdName := "clear"
cmd := exec.Command(cmdName)
cmd.Stdout = os.Stdout
cmd.Run()
Enter fullscreen mode Exit fullscreen mode

It's important to add the cmd.Stdout = os.Stdout line (you can replace os.Stdout with any io.Writer variable) if you want the output of the command to appear somewhere. This is not necessary however if the command does not output anything.

Launching commands in the terminal is always a useful tool, and very welcome in a Go script. To see it in action, I prepared a fun example of a checkerboard that randomly increases a cell value and prints the equivalent number in Japanese (from 0 to 3).

package main

import (
    "fmt"
    "math/rand"
    "os"
    "os/exec"
    "strings"
    "time"
)

func main() {
    h, l := 8, 8
    board := make([]uint8, h * l)
    for i := 0; i < 120; i++ {
        clear()
        cellFlip(rand.Intn(len(board)), board)
        fmt.Println(plotted(l, board))
        time.Sleep(400 * time.Millisecond)
    }
}

func clear() {
    cmd := exec.Command("clear")
    cmd.Stdout = os.Stdout
    cmd.Run()
}

func cellFlip(i int, b []uint8) {
    if b[i] >= 3 {
        return
    }
    b[i]++
}

func plotted(l int, b []uint8) string {
    var s strings.Builder
    s.Grow(len(b) + l)
    for i, cell := range b {
        s.WriteRune(toRune(cell))
        if i%l != l-1 {
            continue
        }
        s.WriteRune('\n')
    }
    return s.String()
}

func toRune(cell uint8) rune {
    var c rune
    switch cell {
    case 0:
        c = 0x53E3
    case 1:
        c = 0x4E00
    case 2:
        c = 0x4E8C
    case 3:
        c = 0x4E09
    default:
        c = 'x'
    }
    return c
}
Enter fullscreen mode Exit fullscreen mode

0x53E3, 0x4E00, 0x4E8C and 0x4E09 are the codes for 口 (ro which is coming from ゼロ/zero), 一 (ichi) , 二 (ni) and 三 (san) that are the first three numbers in Japanese whose codes are referenced from the Unicode and that can be consulted here.

Please also refer to the `os/exec' package to know more about how to launch commands.

Top comments (2)

Collapse
 
jairforero profile image
Jair Forero

Hi!, please Tol undefined :(

Collapse
 
mcaci profile image
Michele Caci • Edited

Hi, sorry I'm just realizing this. From what I see from the code and my memories it could be any number. I need to check this when I 'm back in front of a PC. Thanks for spotting this.

EDIT: I checked the code and correcting the example. Thanks again!