bitmask
bitmask

Reputation: 34628

Can I test for an open stdin stream from within a bash script?

Assume I want to write all input to a script into a logfile, command line and standard in. So, if somebody pipes text to my script, I want to write that into the log as well, but if I'm invoked without input (e.g. from a login shell) the script will block if I try to cat or read standard in, waiting for the user to type something.

Can I somehow test for an open input stream? Or just capture all standard in, if and only if there is standard in?

Upvotes: 4

Views: 605

Answers (1)

epsilon
epsilon

Reputation: 2969

You may use the -t option on command test.

From the man:

-t FD file descriptor FD is opened on a terminal

if [ -t 0 ]; then
  echo "Pipe not open"
else
  echo "Pipe available"
fi

Upvotes: 4

Related Questions