Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo command in Golang

Tags:

echo

go

I'm currently trying to execute a simple echo command in Golang on Linux. My code is the following:

cmd = exec.Command("echo", "\"foo 0x50\"", ">", "test.txt")

_, err = cmd.Output()

if err != nil {
    fmt.Println(err)
}

But test.txt doesn't appear in my folder (even after compile and run the code). That not the first that that I use this method to execute commands and I never thought that I will be block on an echo command.

So how can I fix this code in order to have "foo 0x50" (with the quotes) in the test.txt?

like image 530
Majonsi Avatar asked Oct 17 '16 15:10

Majonsi


1 Answers

You can redirect the stdout like this:

// Remove the redirect from command
cmd := exec.Command("echo", "\"foo 0x50\"")

// Make test file
testFile, err := os.Create("test.txt")
if err != nil {
    panic(err)
}
defer outfile.Close()

// Redirect the output here (this is the key part)
cmd.Stdout = testFile

err = cmd.Start(); if err != nil {
    panic(err)
}
cmd.Wait()
like image 139
Tyler Avatar answered Oct 28 '22 08:10

Tyler