1

i wanted to run this command using golang how can i achieve it using exec.Command

mysqldump -u root -p database_name | mysql -h remote_host -u root -p remote_database_name

please anyone help me

Thanks Mike

Mike Mulaffer
  • 149
  • 2
  • 6

2 Answers2

2

You cannot pass a pipe, which is a shell construct, as a command line argument.

You can execute bash with the -c string option to execute command in the string.

str := "mysqldump -u root -p database_name | mysql -h remote_host -u root -p remote_database_name"
output, err := exec.Command("bash", "-c", str).Output()
if err != nil {
    panic(err)
}
fmt.Println(string(output))

Or you can use (*exec.Cmd).StdoutPipe to pipe the output of one command to the input of another.

c1 := exec.Command("mysqldump", "-u", "root", "-p", "database_name")
out, err := c1.StdoutPipe()
if err != nil {
    panic(err)
}

c2 := exec.Command("mysql", "-h", "remote_host", "-u", "root", "-p", "remote_database_name")
c2.Stdin = out

if err := c2.Start(); err != nil {
    panic(err)
}
if err := c1.Run(); err != nil {
    panic(err)
}
if err := c2.Wait(); err != nil {
    panic(err)
}
mkopriva
  • 35,176
  • 4
  • 57
  • 71
0

Did you try below? Refer here.

package main

import (
    "log"
    "os/exec"
)

func main() {
    cmd := exec.Command("mysqldump", "-u", "root", "-p", "database_name", "|", "mysql", "-h", "remote_host", "-u", "root", "-p", "remote_database_name")
    err := cmd.Run()
    if err != nil { 
        log.Printf("Command finished with error: %v", err)
    }
}