Bash – Testing for a script that is waiting on stdin

bashscriptingstdin

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.

Best Answer

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:

#!/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"

Example runs:

$ 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