当bash调用Go程序输入时出现无限循环。

huangapple go评论86阅读模式
英文:

infinite loop when bash call Go program input

问题

我写了一个bash脚本来自动下载我的Go程序并安装到我的Linux机器上。我可以使用curl来下载,但是当我的Go程序提示用户输入时,它会进入无限循环。错误显示EOF错误。

有人对此有任何想法吗?

Install.sh

#!/bin/bash
set -e
set -o noglob

curl https://coderkk.net/ReadInput -o ReadInput
chmod a+x ReadInput
./ReadInput

ReadInput.go

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	var text string

	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print("Please enter your name here: ")
		text, _ = reader.ReadString('\n')
		text = strings.Replace(text, "\n", "", -1)
		if text != "" {
			break
		}
	}

	fmt.Printf("Hi %s\n", text)
}
英文:

I wrote a bash script to automate download my Go program and install to my linux machine. I can via the curl to download but when my Go program prompt the user input, it go to infinite loop. The error shows EOF error.

Do anyone have any idea about it?

Install.sh

#!/bin/bash
set -e
set -o noglob

curl https://coderkk.net/ReadInput -o ReadInput
chmod a+x ReadInput
./ReadInput

ReadInput.go

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	var text string

	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print("Please enter you name here : ")
		text, _ = reader.ReadString('\n')
		text = strings.Replace(text, "\n", "", -1)
		if text != "" {
			break
		}
	}

	fmt.Printf("Hi %s\n", text)
}

答案1

得分: 1

问题与Go无关,尽管你不应忽略reader.ReadString可能出现的任何潜在错误,但问题是由于你调用下载的脚本的方式不正确。

管道将curl的输出转换为shstdin。这没问题,但是你的脚本需要来自终端的stdin,而现在已经丢失了。

将你的调用方法更改为以下内容:

sh -c "$(curl -sfL https://coderkk.net/install.sh)"

这将将脚本的内容传递给sh解释器,同时保留用户的终端stdin

英文:

The problem is not related to Go - although you shouldn't ignore any potential errors from reader.ReadString - it is due to how you are invoking your downloaded script.

The pipe takes the output of curl and turns that into the stdin for sh. This is fine but your script requires stdin from the terminal - which is now lost.

Change your invocation method to something like this:

sh -c "$(curl -sfL https://coderkk.net/install.sh)"

this will pass the contents of your script to the sh interpreter but preserve the user's terminal stdin.

huangapple
  • 本文由 发表于 2021年8月31日 19:46:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/68998105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定