1

I tried to use a basic bash command read to capture a single character from a keyboard. But it seemed difficult to get the output even I try several ways.

Sample code:

fmt.Println(exec.Command("read", "-t", "5", "-n", "1").Output())

Its meaning is "waiting for 5 seconds to get 1 input character from the keyboard". From code above I expected to see my input character printed out together with its error but what do I get is

Output:

[] exit status 1

This output is just immediately printed in lesser than 1 second which conflicts to "-t", "5" argument of read command which stands for waiting for 5 second. I try to type some character within 1 second but it seems doesn't work at all.

BTW, if try this

fmt.Println(exec.Command("echo", "\"Hi!\"").Output())

output:

[34 104 105 34 10] <nil>

It seems work here with simple echo here.

fronthem
  • 4,011
  • 8
  • 34
  • 55
  • Read is a bash command, not an executable in your PATH like echo. Maybe invoking read inside bash could work. I'd suggest to find a Go-only solution. – Volker Jan 20 '16 at 16:18
  • @Volker I just want to capture `spacebar` that's all. Do you have any suggestion for a simple go-only solution? – fronthem Jan 20 '16 at 16:27

1 Answers1

2

You're not providing the command with stdin, so there's nothing it can read and it exits immediately.

If you want to hook it up the same stdin as the calling program, you can use:

cmd := exec.Command("read", "-t", "5", "-n", "1")
cmd.Stdin = os.Stdin
out, err := cmd.CombinedOutput()

fmt.Println("error:", err)
fmt.Printf("output: %q\n", out)

This however won't output anything, since the /usr/bin/read script isn't going to print anything. You probably want the shell builtin read to be called in the context of a shell. This would print the character read:

cmd := exec.Command("bash", "-c", "read -t 5 -n 1 C && echo -n $C")
cmd.Stdin = os.Stdin

But in the end, you should probably just read directly from stdin in go.

JimB
  • 104,193
  • 13
  • 262
  • 255
  • Thank for your answer @JimB. I've tried your code, it's sound good, but I got "" from `out` every times I input. – fronthem Jan 20 '16 at 16:25
  • @terces907: that's because `read` isn't printing any output. What are you trying to do? – JimB Jan 20 '16 at 16:30
  • I just want to get a given input character. – fronthem Jan 20 '16 at 16:33
  • @terces907: I added some more info. Why not just do it in Go? – JimB Jan 20 '16 at 16:41
  • I just want to capture `spacebar` which input from keyboard without entering from user. For sure, it can be done by code you've given me above. Any simpler way for golang-only code please suggest @JimB. – fronthem Jan 20 '16 at 16:43
  • 1
    @terces907: bash puts the tty in raw mode for `read`. See http://stackoverflow.com/questions/15159118/read-a-character-from-standard-input-in-go-without-pressing-enter, and http://stackoverflow.com/questions/14094190/golang-function-similar-to-getchar – JimB Jan 20 '16 at 16:49