-2

I want to execute

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

using exec.Command method of Golang.

My code goes like this :

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

but this fails. I guess I am not able to escape "|". I have tried "\|", but this also fails. What am I doing wrong??

Shubham
  • 21
  • 1
  • 4
  • `|` doesn't need escaping. What is the error, what does `this fails` mean? – Panagiotis Kanavos Feb 03 '20 at 10:51
  • The error goes like this : ```panic: exit status 1 goroutine 1 [running]: main.main() /Users/shubhamsaurav/Downloads/postgresDump/testsql.go:13 +0x143 exit status 2 . ``` – Shubham Feb 03 '20 at 10:52
  • BTW what you posted is *not* one command followed by arguments. It's an entire script. The results of the first command, `cat` with arguments `database_dump_1.sql` are piped to the second one, `docker` ...`. Have you tried running the entire string as-is? – Panagiotis Kanavos Feb 03 '20 at 10:53
  • You mean like this ?? ```options := []string{"out.sql | docker exec -i my_postgres psql -U postgres"} cmd, err := exec.Command("cat", options...).Output() ``` – Shubham Feb 03 '20 at 10:56
  • Or like this ```cmd, err := exec.Command("cat out.sql | docker exec -i my_postgres psql -U postgres").Output() ``` . ??? – Shubham Feb 03 '20 at 10:57

1 Answers1

3

As the docs say, pipelines are a shell feature which is not supported by this package:

Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells.

As a quick workaround, you can try calling shell with the entire command as an argument, for example:

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

Notice that cmd must be a string, not a slice.

bereal
  • 32,519
  • 6
  • 58
  • 104