有没有办法确定脚本是否在stdin上等待并导致命令在检测到时退出?
这是一个例子,我正在执行的命令需要很长时间才能运行,但在启动w / o提示之前它也会提示输入.我想知道命令实际上在做什么而不仅仅是等待.
提供了以下脚本名为./demo
- #!/bin/bash
- read
有没有办法检测读取正在等待stdin?就像是
- failifwaitingonstdin | ./demo
一旦检测到读取命令,它将立即返回.
更新:
人们建议像期待和是的程序.在深入了解之后,我看到他们如何能够支持这种交互方式.他们经常使用fputs将’y’写入stdout.而不是无限地执行此操作,只要fputs在写入stdout时返回,我就可以简单地返回错误.
如果您对脚本和/或命令更具体,那将非常有用.但是如果你想要做的是测试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"
示例运行:
- $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