1

I have a shell script where I have a if statement based off of the number output lines output from another call. (In my case do something there is more that 1 line of output).

LINES=$(function_call | wc -l)
if [ "$LINES" -gt 1 ]
  then
    do_stuff
fi

What I would like however is not to consume the output (ie still have it appear in stdout), but still have the script do the same thing.

3
  • What is your question here ? You already saved the output from your function_call to a variable. What else do you mean by "not consuming the output" ? What is the expected output and what do you want to do with it ? Your question is really vague. – MelBurslan Apr 19 '16 at 15:28
  • Is this a zen question? How do you count lines of output without reading it? My only constructive thought here is to use tee to (additionally) save the output to a file, or to saved the output to a variable. Either way, the output will be "consumed", though. – Jeff Schaller Apr 19 '16 at 15:34
  • I would like to be able to get the line count (so I can make decisions based off of it) and have the output appear in stdout. – Chris Apr 19 '16 at 15:37
4

Use tee (here assuming a system with support for /dev/fd/<n>):

{ 
  lines=$(function_call 3>&- | tee -a /dev/fd/3 | wc -l)
} 3>&1
if [ "$lines" -gt 1 ];  then
  do_stuff
fi

On Linux that has an odd implementation of /dev/fd/<n>, if stdout is redirected to a file, the output will be inserted at the end of that file even if the current position of stdout in the script in that file is not at the end (in general, that would be OK though as it's rare for stdout to be going inside a file).

Alternatively, you could do

{ 
  lines=$(function_call 3>&- | sed -ne 'w /dev/fd/3' -e '$=')
} 3>&1

Or:

{ 
  lines=$(function_call 3>&- | awk '{print > "/dev/fd/3"}; END {print NR}')
} 3>&1

(beware that depending on the sed or awk implementation, it may give one more than wc -l if function_call outputs extra data after the last newline character).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.