【问题标题】:How to escape "\" in exec.Command in Golang? [duplicate]如何在 Golang 的 exec.Command 中转义“\”? [复制]
【发布时间】:2020-02-03 10:45:18
【问题描述】:

我要执行

cat database_dump_1.sql | docker exec -i my_postgres psql -U postgres

使用 Golang 的 exec.Command 方法。

我的代码是这样的:

options := []string{"out.sql", "|", "docker", "exec", "-i", "my_postgres", "psql", "-U", "postgres"}
    cmd, err := exec.Command("cat", options...).Output()
    if err != nil {
        panic(err)
    }
    fmt.Println(string(cmd))

但这失败了。我想我无法逃脱“|”。我试过“\|”,但这也失败了。 我做错了什么??

【问题讨论】:

  • | 不需要转义。错误是什么,this fails是什么意思?
  • 错误如下:panic: exit status 1 goroutine 1 [running]: main.main() /Users/shubhamsaurav/Downloads/postgresDump/testsql.go:13 +0x143 exit status 2 .
  • 顺便说一句,您发布的内容不是一个命令后跟参数。这是一个完整的脚本。第一个命令的结果 cat 带有参数 database_dump_1.sql 被传送到第二个命令 docker ...`。您是否尝试过按原样运行整个字符串?
  • 你的意思是这样的?? options := []string{"out.sql | docker exec -i my_postgres psql -U postgres"} cmd, err := exec.Command("cat", options...).Output()
  • 或者喜欢这个cmd, err := exec.Command("cat out.sql | docker exec -i my_postgres psql -U postgres").Output() 。 ???

标签: go


【解决方案1】:

正如docs 所说,管道是这个包不支持的外壳功能:

与来自 C 和其他语言的“系统”库调用不同,os/exec 包有意不调用系统 shell,也不扩展任何 glob 模式或处理通常由 shell 完成的其他扩展、管道或重定向。

作为一种快速解决方法,您可以尝试使用整个命令作为参数调用 shell,例如:

cmd := "cat out.sql | docker exec -i my_postgres psql -U postgres"
exec.Command("sh", "-c", cmd)

注意cmd 必须是字符串,而不是切片。

【讨论】:

    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 2018-04-04
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    相关资源
    最近更新 更多