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?
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.
Cmd represents an external command, similar to the Go built-in 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With