英文:
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的输出转换为sh
的stdin
。这没问题,但是你的脚本需要来自终端的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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论