bash – 测试正在等待stdin的脚本

前端之家收集整理的这篇文章主要介绍了bash – 测试正在等待stdin的脚本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法确定脚本是否在stdin上等待并导致命令在检测到时退出

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

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

  1. #!/bin/bash
  2.  
  3. read

有没有办法检测读取正在等待stdin?就像是

  1. failifwaitingonstdin | ./demo

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

更新:

人们建议像期待和是的程序.在深入了解之后,我看到他们如何能够支持这种交互方式.他们经常使用fputs将’y’写入stdout.而不是无限地执行此操作,只要fputs在写入stdout时返回,我就可以简单地返回错误.

如果您对脚本和/或命令更具体,那将非常有用.但是如果你想要做的是测试stdin来自哪里,这个示例脚本将为你演示:
  1. #!/bin/bash
  2. if [[ -p /dev/stdin ]]
  3. then
  4. echo "stdin is coming from a pipe"
  5. fi
  6. if [[ -t 0 ]]
  7. then
  8. echo "stdin is coming from the terminal"
  9. fi
  10. if [[ ! -t 0 && ! -p /dev/stdin ]]
  11. then
  12. echo "stdin is redirected"
  13. fi
  14. read
  15. echo "$REPLY"

示例运行:

  1. $echo "hi" | ./demo
  2. stdin is coming from a pipe
  3. $./demo
  4. [press ctrl-d]
  5. stdin is coming from the terminal
  6. $./demo < inputfile
  7. stdin is redirected
  8. $./demo <<< hello
  9. stdin is redirected
  10. $./demo <<EOF
  11. goodbye
  12. EOF
  13. stdin is redirected

猜你在找的Bash相关文章