[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: read built-in command has a problem in shell function

From: Greg Wooledge
Subject: Re: read built-in command has a problem in shell function
Date: Mon, 11 Oct 2021 07:43:59 -0400

On Mon, Oct 11, 2021 at 03:28:18PM +0900, Hyunho Cho wrote:
> If i want to know whether there are input available from stdin
> then i use "read -t 0" command like this
> if read -t 0; then    # first check input available
> while read line; do ... done
> ...
> fi

What are you actually trying to do?  What problem do you have, that
you think "checking for available input" is going to solve?

> sh$ myfunc <<< 111           # OK
> yes
> sh$ echo 111 | myfunc        # OK
> yes
> sh$ cat foo.c | myfunc        # NOT WORK!
> sh$ date | myfunc               # NOT WORK!

As others have already pointed out, you have a race condition.  I'm not
going to focus on that.  I'm trying to figure out what you were trying
to do.

Based on these patterns, it looks like you were trying to write a
function which can either have input piped to it, or read input from
the terminal.  And for whatever reason (I can't guess at this point),
you wanted the function to change its behavior based on whether it was
reading from a pipeline.

If this is the case, then what you want is "test -t", which tests whether
stdin is a terminal.

myfunc() {
    if test -t 0; then
        echo "stdin is a terminal, so do Thing One"
        echo "stdin is not a terminal, so do Thing Two"
        local REPLY
        while read -r; do

reply via email to

[Prev in Thread] Current Thread [Next in Thread]