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: Greg Wooledge
Subject: Re: How to test if stdin is empty, if not empty print to stdout, otherwise do something else.
Date: Wed, 25 Mar 2020 08:22:08 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

The problem with this thread, as with all of Peng Yu's threads, is that
nobody knows what the actual GOAL is.  Peng Yu will never reveal the goal,
either, no matter how many times you ask.

I can think of at least two possible goals which might drive someone to
ask how to test whether stdin has input available.

(1) "I want to write a utility that can either take data as an argument,
    or read data from stdin.  I want it to do the correct thing
    automatically, without having to pass a --stdin option or whatever."

    In this case, the test is simply reversed.  Don't try to test whether
    stdin has input available.  Test whether an argument was passed.

    thing() {
      if [[ $1 ]]; then
        stuff "$1"
      else
        local in
        in=$(cat; printf x)
        in=${in%x}
        # Or, in=$(cat) if you want to strip newlines.  Or, read -r in if
        # you only want one line of input, with newline stripped.
        stuff "$in"
      fi
    }

(2) "I'm writing an keyboard-event-driven user interface that should handle
    keyboard presses whenever they occur, but should not block to wait for
    them."

    Video games in bash.  Very poor implementation choice.  But here, you
    would actually benefit from the read -t 0 feature that was added
    somewhere in the 4.x releases.  You probably have some sort of main
    loop that's running the game, and you can stick a call to read -t 0
    somewhere in that loop.  When input becomes available, handle it.

So, you (the intelligent reader) can see why knowing the goal helps inform
the answers, and therefore, why it's vital to reveal the goal.



reply via email to

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