有没有一种方法来确定脚本是否正在等待标准input,并导致命令退出,如果检测到?
下面是一个例子,我正在执行的命令需要很长时间才能运行,但是在启动w / oa提示符之前,它也会提示input。 我想知道命令实际上在做什么,而不是等待。
提供以下脚本称为./demo
#!/bin/bash read
有没有办法检测到读取正在等待stdin? 就像是
failifwaitingonstdin | ./demo
一旦检测到读取命令,将马上返回。
更新:
人们build议像预期和是的程序。 在深入挖掘之后,我看到他们如何能够支持这种互动风格。 他们不断地使用fputs来写'y'到stdout。 而不是无限的这样做,只要fputs在写入stdout时返回一个错误。
如果你对脚本和/或命令有更多的了解,那真的会有帮助。 但是,如果你想要做的是testing标准input来自哪里,这个示例脚本将为你演示:
#!/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"
示例运行:
$ 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
如果你在Linux上,你可以使用strace来查看进程是否试图从stdin读取。 其他平台也有类似的程序(例如dtrace , ktrace或truss )。
通过将yes的输出提供给有问题的命令,您可以完全避免这个问题。
如果你正在编写脚本:bash的read内build需要超时选项:
read -p prompt -t 5 var # 5s timeout
如果没有,你可以使用expect ,或者只是yes ,假的用户交互。
不知道你想做什么,我会争辩说你应该写脚本,以便你总是知道它是否会要求stdin。 不pipe是这样的,还是将某些东西传递给可能需要标准input的命令,但这可能不是最好的主意。