-3

I am trying to execute MySQL query which gives me the output as CSV file to the specified directory.

func executeCommand(){
    cmd := exec.Command("/usr/local/mysql/bin/mysql", "-e", "-hlocalhost", "-P3131", "-uroot", "-pmyPassword", "dbName",  "> /path/to/output/folder/fileName.csv")
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err = cmd.Run()
    if err != nil {
        fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
    }
    fmt.Println("Result: " + out.String())
}

I am getting the following error:

exit status 1: mysql: [Warning] Using a password on the command line interface can be insecure.

When I removed the output directory path then there is no error. But I need my output generated file to the specified directory.

I also tried replacing > with source but no luck. Also, when I'm running the same on Terminal it is working as intended but I am failing to replicate the same through Go.

/usr/local/mysql/bin/mysql -e "select * from tableName" -u root -p -h localhost -P 3131 dbName > /path/to/output/folder/fileName.csv

I tried searching on SO but couldn't find anything relevant. Any help would be appreciated.

Abhinav
  • 83
  • 1
  • 10
  • Whosoever has downvoted my question, please have the courtesy to write the reason for the same. Thanks. – Abhinav Jan 08 '20 at 06:39
  • https://stackoverflow.com/questions/41037870/go-exec-command-run-command-which-contains-pipe – Adrian Jan 08 '20 at 15:38

1 Answers1

3

The > is a shell metacharacter for output redirection. When you run a command in the shell, the shell pre-parses your command and does special things with input/output redirection. It does not pass the redirection metacharacters to the program. But when you use exec.Command(), you only give the arguments you want to pass to the command.

If you want to save the output of the command, you need to work with your cmd.Stdout buffer.

See also How to execute Mysql Script in golang using exec.Command

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • I saw your answer, but I just wanted to know, what should I write in place of '<'; source? Because using source I couldn't achieve the result as I'm stuck with the same error. And thanks for such an informative explanation. – Abhinav Jan 07 '20 at 21:30
  • You need to write code to write to the command's standard input and read from its standard output. Refer to https://golang.org/src/os/exec/example_test.go for examples. – Bill Karwin Jan 07 '20 at 21:42
  • 1
    I worked with my cmd.Stdout buffer and save that buffer into the file. Earlier I was stuck with exec.Command thinking it will directly output it to the file. Thanks for clearing this out. – Abhinav Jan 08 '20 at 07:27