在程序开始时读取所有 stdin 会阻止在程序期间从 stdin 读取

Reading all of stdin at program start prevents reading from stdin during the program

我有一个 golang 程序可以为 jq 做一个简单的 repl。我希望能够在程序启动时从 stdin 读取输入到一个临时文件中,这样我就可以将 repl 与管道输入一起使用。

cat file.json | jqrepl

但是,当我使用扫描仪或 reader 从标准输入读取时,我到达了标准输入的 EOF,然后我无法再接受来自标准输入的主 repl 循环的输入。 Readline 立即失败,因为它处于 EOF。

我已经尝试推迟 Reader.UnreadByte、关闭扫描器、大量 "seek(0)" 以及其他对标准输入的原始操作。

有没有办法重置标准输入以便再次读取?理想情况下,我会读到 EOF,将其保存到临时文件,然后进入 repl 模式。

谢谢!

(我想你在 "I can no longer accept input from stdin for the main repl loop" 中提到的 stdin 指的是交互式用户输入。)

这样试试:

[STEP 101] # cat foo.sh
while read line; do
    printf '> %s\n' "$line"
done

# close stdin
exec 0<&-
# reopen stdin to /dev/tty
exec 0< /dev/tty

read -p 'Input something: ' v
printf 'You inputted: %s\n' "$v"
[STEP 102] # printf '%s\n' foo bar | bash ./foo.sh
> foo
> bar
Input something: hello world
You inputted: hello world
[STEP 103] #