Is there something wrong with my exec.Command format with grep in Golang? [duplicate]

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


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