I want to run an equivalent to psql -lqt | cut -d | -f 1 | grep -qw ; echo $?
So I’m trying to pipe the output of a command to the input of the next command and eventually read the output of the grep or the last exit value.
(I’m checking if a db with a specific name already exists).
I’m trying to concatenate a few bash commands using os.Pipe. When I’m trying to read the content of the the readers in the process, I see that the length of the byte slice passing through is 0. If I replace the writers with os.Stdout I see the correct output.
Could someone please point me to what I’m doing wrong?
Relevant part of the code:
dbName := dbInfo[“name”].(string)
reader1, writer1, _ := os.Pipe()
reader2, writer2, _ := os.Pipe()
var outBuff bytes.Buffer
//Each writer writes to its reader, they're connected through the pipe.
cmd1 := exec.Command("/bin/bash", "-c", "psql -lqt")
cmd1.Stdout = writer1
cmd2 := exec.Command("/bin/bash", "-c", `cut -d | -f 1`)
cmd2.Stdin = reader1
cmd2.Stdout = writer2
cmd3String := fmt.Sprintf(`grep -qw '%s'`, dbName)
cmd3 := exec.Command("/bin/bash", "-c", cmd3String)
cmd3.Stdin = reader2
cmd3.Stderr = &outBuff //If a db doesn't exist I'm expecting an error.
go func() {
err = cmd1.Run()
if err != nil {
log.Fatalf("Issue with running the command %s: %vn",
cmd1.String(), err)
}
writer1.Close()
}()
r1Info, _ := reader1.Stat()
content := make([]byte, r1Info.Size())
reader1.Read(content)
fmt.Printf("%s", content)
go func() {
err = cmd2.Run()
defer writer2.Close()
if err != nil {
log.Fatalf("Issue with running the command %s: %vn",
cmd2.String(), err)
}
}()
r2Info, _ := reader2.Stat()
content = make([]byte, r2Info.Size())
reader2.Read(content)
fmt.Printf("%s", content)
go func() {
err = cmd3.Run()
if err != nil {
log.Fatalf("Issue with running the command %s: %vn",
cmd3.String(), err)
}
}()
exitVal := outBuff.String()
if len(exitVal) != 0 {
//If the database doesn't exist, we create it.
query := fmt.Sprintf(`CREATE DATABASE %s;`, dbName)
_, err = dbPointer.Exec(query)
if err != nil {
log.Fatalf("Couldn't run the query %s: %vn", query, err)
}
}
Thanks!