help-bash
[Top][All Lists]
Advanced

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

Re: How to test if stdin is empty, if not empty print to stdout, otherwi


From: Peng Yu
Subject: Re: How to test if stdin is empty, if not empty print to stdout, otherwise do something else.
Date: Tue, 24 Mar 2020 19:22:06 -0500

`empty` means as if it is read from /dev/null.

I end up with something like this. Is it robust? I am not sure if can
cover all the corner cases.

function f {
        read -d '' -n1
        if [[ $REPLY ]]; then
                echo -n "$REPLY"
                cat
        else
                echo 'No input from stdin'
        fi
}

{ echo; seq 3; } | f

1
2
3
seq 10 13 | f
10
11
12
13
f < /dev/null
No input from stdin



On 3/24/20, Eli Schwartz <address@hidden> wrote:
> On 3/24/20 7:43 PM, Peng Yu wrote:
>> Hi,
>>
>> ifne from moreutils can work similar to this goal. But it is an
>> external program.
>>
>> I'd like to test if stdin is not empty, then print to stdout of the
>> input.
>>
>> But the following code is not robust for this goal. Is there a robust
>> way to do so in bash? Thanks.
>>
>> $ function f {
>>      if read -n1; then
>>              echo "$REPLY"
>>              cat
>>      else
>>              echo 'No input from stdin'
>>      fi
>> }
>>
>> $ { echo; seq 3; } | f
>>
>> 1
>> 2
>> 3
>> $ seq 10 13 | f
>> 1
>> 0
>> 11
>> 12
>> 13
>> $ f < /dev/null
>> No input from stdin
>
> The problem you are having here is, how do you define "empty"?
>
> $ printf '%s\n' '' | { read; echo ret=$?; declare -p REPLY; }
> ret=0
> declare -- REPLY=""
> $ printf '%s' '' | { read; echo ret=$?; declare -p REPLY; }
> ret=1
> declare -- REPLY=""
> $ help read
> [...]
>     Exit Status:
>     The return code is zero, unless end-of-file is encountered, read
> times out
>     (in which case it's greater than 128), a variable assignment error
> occurs,
>     or an invalid file descriptor is supplied as the argument to -u.
> $
>
> And the thing is, that you're currently using the return value of read
> to determine that you *do* have input, that input is of length zero, and
> that input is terminated by a newline of length 1 (before reaching an EOF).
>
> If you wanted to check whether you have "interesting" input, then don't
> check the return value of `read`, instead, analyze $REPLY to see whether
> you consider it interesting, for example, if [ -n "$REPLY" ] to see if
> it is zero-length. If you don't consider whitespace to be interesting,
> then you can do similar checks if $REPLY contains characters other than
> [:space:]
>
> --
> Eli Schwartz
> Arch Linux Bug Wrangler and Trusted User
>
>


-- 
Regards,
Peng



reply via email to

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