测试正在等待标准输入的脚本

Noa*_*ell 7 scripting bash stdin

有没有办法确定脚本是否正在等待 stdin 并在检测到命令时退出?

这是一个例子,我正在执行的命令需要很长时间才能运行,但它也会在启动 w/oa 提示之前提示输入。我想知道该命令实际上是在做某事,而不仅仅是在等待。

提供了以下名为 ./demo 的脚本

#!/bin/bash

read
Run Code Online (Sandbox Code Playgroud)

有没有办法检测读取正在等待标准输入?就像是

failifwaitingonstdin | ./demo
Run Code Online (Sandbox Code Playgroud)

一旦检测到读取命令,它将立即返回。

更新:

人们已经建议了诸如expect 和yes 之类的程序。在深入研究 yes 之后,我看到他们如何能够支持这种交互方式。他们不断地使用 fputs 将“y”写入标准输出。我可以简单地在 fputs 在写入标准输出时返回时立即返回错误,而不是无限地执行此操作。

Den*_*son 15

如果您对脚本和/或命令更加具体,那将非常有帮助。但是,如果您想要做的是测试 stdin 的来源,此示例脚本将为您演示:

#!/bin/bash
if [[ -p /dev/stdin ]]
then
    echo "stdin is coming from a pipe"
fi
if [[ -t 0 ]]
then
    echo "stdin is coming from the terminal"
fi
if [[ ! -t 0 && ! -p /dev/stdin ]]
then
    echo "stdin is redirected"
fi
read
echo "$REPLY"
Run Code Online (Sandbox Code Playgroud)

示例运行:

$ echo "hi" | ./demo
stdin is coming from a pipe
$ ./demo
[press ctrl-d]
stdin is coming from the terminal
$ ./demo < inputfile
stdin is redirected
$ ./demo <<< hello
stdin is redirected
$ ./demo <<EOF
goodbye
EOF
stdin is redirected
Run Code Online (Sandbox Code Playgroud)