Is there a way to determine if a script is waiting on stdin and cause the command to exit if detected?
Here's an example, the command I'm executing takes a long time to run, but it will also prompt for input before starting w/o a prompt. I want to know the command is actually doing something and not just waiting.
Provided the following script called ./demo
#!/bin/bash
read
Is there a way to detect that read is waiting on stdin? Something like
failifwaitingonstdin | ./demo
Which would immediately return as soon as the read command was detected.
Updated:
Folks have suggested programs like expect and yes. After digging through yes, I see how they're able to support this style of interaction. They're constantly using fputs to write 'y' to stdout. Instead of doing this infinitely, I can simply return an error as soon as fputs returns on a write to stdout.
It would really help if you were a lot more specific about your script and/or command. But in case what you want to do is test where stdin is coming from, this example script will demonstrate that for you:
Example runs:
Without knowing what you're trying to do I'd argue you should be writing the script so that you always know if it's going to ask for stdin or not. Either that or pipe something into the command that's likely to be wanting something from stdin, but that's probably not the best idea.
If you're on Linux you could use
strace
to see if the process is trying to read from stdin. Other platforms have similar programs (e.g.dtrace
,ktrace
, ortruss
).You might be able to avoid the issue altogether by feeding the output of
yes
to the command in question.If you are writing the scripts: bash's
read
builtin takes a timeout option:If not, you can use
expect
, or justyes
, to fake user interaction.