Running Shell Commands in Golang

In Go language, you can execute shell commands using the os/exec package. Here is a simple example code:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls", "-l")
    output, err := cmd.Output()
    if err != nil {
        fmt.Println("Error executing command: ", err)
        return
    }

    fmt.Println(string(output))
}

The exec.Command function in the above code can be used to create a Cmd struct, representing a command to be executed. The command can then be executed and the output results can be retrieved using the Cmd’s Output method.

Please be extremely cautious when executing shell commands to avoid potential security risks that could lead to program attacks. It is recommended to avoid directly concatenating user-input commands and instead use parameterized methods to execute commands.

bannerAds