In the question "Testing if a file descriptor is valid", a test is sought for testing whether a file descriptor is opened or not.
The answers all focus on testing whether the file descriptor is opened for output, but how may one test whether the file descriptor is opened for input?
This came up in a comment thread for an answer to another question, where the answer said, paraphrasing,
if [ -n "$1" ]; then # read input from file "$1" (we're assuming it exists) elif [ ! -t 0 ]; then # read input from standard input (from pipe or redirection) else # no input given (we don't want to read from the terminal) fi
The problem with
[ ! -t 0 ] is that the
-t test is true if the file descriptor is open and associated with a terminal. If the test is false, then the descriptor is either closed, or not associated with a terminal (i.e. we're reading from a pipe or redirection). Testing with
[ ! -t 0 ] is therefore not a guarantee that the file descriptor is even valid.
How to determine whether it's valid (so that
read would not complain) or whether it's closed?