Home >Backend Development >Golang >How Can I Get the Output of System Commands as a String in Go?

How Can I Get the Output of System Commands as a String in Go?

Barbara Streisand
Barbara StreisandOriginal
2025-01-02 18:17:411035browse

How Can I Get the Output of System Commands as a String in Go?

Getting the Output of System Commands in Go

In Go, retrieving the output of system commands can be accomplished using various commands found in the exec and os packages. However, a convenient way to obtain the output directly as a string is available.

Solution:

The preferred method to capture the output of system commands is to utilize the Output() method of the exec.Command type. This method returns the standard output of the executed command as a byte array. Here's an example:

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("date").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("The date is %s\n", out)
}

In this example, the out variable contains the standard output in the form of a byte array. You can easily convert it to a string using the string(out) expression.

Additional Options:

Furthermore, the exec.Command type has a CombinedOutput() method, which retrieves both standard output and standard error. This method can be utilized by replacing Output() with CombinedOutput() in the code snippet above.

The above is the detailed content of How Can I Get the Output of System Commands as a String in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn