在程序启动时读取所有stdin会阻止在程序期间从stdin读取

时间:2017-05-17 06:19:02

标签: bash go pipe stdin read-eval-print-loop

我有一个golang程序,可以为jq进行简单的repl。我希望能够在程序启动时将stdin的输入读入临时文件,因此我可以使用带有管道输入的repl。

cat file.json | jqrepl

但是,当我从stdin读取时,无论是使用扫描仪还是读取器,我都会到达stdin的EOF,然后我再也无法接受来自stdin的主repl循环输入。 Readline立即失败,因为它在EOF。

我尝试推迟使用Reader.UnreadByte,关闭扫描程序,以及大量的" seek(0)"以及stdin上的其他原始操作。

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

谢谢!

1 个答案:

答案 0 :(得分:1)

(我想你在&#34中提到的 stdin ;我不能再接受来自 stdin 的输入来进行主要的repl循环&#34; < / em>指的是交互式用户输入。)

试试这样:

[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] #