Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the output of a system command in Go?

Tags:

go

Let's say I want to run 'ls' in a go program, and store the results in a string. There seems to be a few commands to fork processes in the exec and os packages, but they require file arguments for stdout, etc. Is there a way to get the output as a string?

like image 668
marketer Avatar asked Dec 09 '09 21:12

marketer


People also ask

How do you read command line arguments in Golang?

In Golang, we have a package called as os package that contains an array called as “Args”. Args is an array of string that contains all the command line arguments passed. The first argument will be always the program name as shown below. Output: Here, you can see it is showing the program name with full path.

What is CMD in Golang?

Cmd represents an external command, similar to the Go built-in os/exec.

What is os exec?

In computing, exec is a functionality of an operating system that runs an executable file in the context of an already existing process, replacing the previous executable. This act is also referred to as an overlay.


1 Answers

There is an easier way now:

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) } 

Where out is the standard output. It's in the format []byte, but you can change it to string easily with:

string(out) 

You can also use CombinedOutput() instead of Output() which returns standard output and standard error.

exec.Command

like image 86
Fatih Arslan Avatar answered Oct 09 '22 14:10

Fatih Arslan