英文:
achieve mysql dump and restore in one command in golang
问题
我想使用Golang运行这个命令,如何使用exec.Command实现呢?
mysqldump -u root -p database_name | mysql -h remote_host -u root -p remote_database_name
请有人帮帮我。
谢谢
Mike
英文:
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
答案1
得分: 2
你不能将管道(pipe)作为命令行参数传递,因为管道是一个shell构造。
你可以使用-c string
选项在bash
中执行命令字符串。
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))
或者你可以使用(*exec.Cmd).StdoutPipe
将一个命令的输出导入到另一个命令的输入。
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)
}
英文:
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)
}
答案2
得分: 0
你尝试过下面的方法了吗?请参考这里。
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("命令执行出错: %v", err)
}
}
英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论