在golang中一起执行bash echo和nc [重复]

This question already has an answer here:

This is probably a simple problem. Working on a linux machine and I'm trying to send a command to the shell from a go program. I have a server listening for requests. This line of code is giving me problems though.

cmd := exec.Command("echo -n 'hello' | nc localhost 3333")

The rest of my code runs the command properly...

However it's just recognizing it as an echo argument with the rest being part of the string it's echoing. I want to pipe the echo to nc to send the message to server.

I have tried rearranging it, such as in this manner:

cmd := exec.Command("echo", "-n", "'hello' | nc localhost 3333")

But they produce the same result, or an error:

executable file not found $PATH

How do I execute echo and a piped command like nc together in this manner from a go script.

</div>

|, >, <, &,...,cd,... and many more were shell builtins, these were interpreted by shell and executed accordingly.

So you need to call shell, and execute your command with -c flag, mentioning shell to execute the following argument as a command.

package main

import (
    "os"
    "os/exec"
)

func main() {
    sh := os.Getenv("SHELL") //fetch default shell
    //execute the needed command with `-c` flag
    cmd := exec.Command(sh, "-c ", `echo -n 'hello' | grep "h"`)
    cmd.Stdout = os.Stdout
    cmd.Run()
}

Here I was using grep, because I don't have nc