-2

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.

Volker
  • 40,468
  • 7
  • 81
  • 87
Jamin
  • 1,362
  • 8
  • 22
  • 1
    Pipes are shell syntax, which is unlikely to be available when running commands from other languages. There is probably a way to pass something on standard input to a `Command`. – l0b0 Oct 12 '18 at 01:36
  • Duplicate. You'll find lots of similar questions here. – Volker Oct 12 '18 at 06:02
  • 1
    There is no reason to execute echo with a static argument. Just assign a strings.Reader to [Command.Stdin](https://golang.org/pkg/os/exec/#Cmd), for instance. – Peter Oct 12 '18 at 06:20

1 Answers1

2

|, >, <, &,...,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

nilsocket
  • 1,441
  • 9
  • 17