0

new to bash. i want a "while read line" loop the gets input from a command-in this case, grep. i want the read to read each line the grep returns and insert it as a string to the "line" var. in case the grep returns no results, i still want it to enter the loop so i can printf something and then continue. will it work? here's the code segement:

while read -r line: do

    ...(irrelevent)...

        done<$(grep $id ${arrpre[$j]}.course)

${arrpre[$j]}.course is the name of the file. tnx for the help!

5
  • 1
    Do you want to read from the output of grep, or from a file named as the output of grep? This code is doing the latter. Commented Nov 13, 2017 at 18:26
  • ...if you want the loop to iterate over the output itself, that would be either done < <(grep ...) or done <<<"$(grep ...)" Commented Nov 13, 2017 at 18:28
  • ... Or grep ... | while .... Commented Nov 13, 2017 at 18:29
  • @JohnBollinger, ...though that's subject to the pitfalls described in BashFAQ #24. Commented Nov 13, 2017 at 18:29
  • That's true, @CharlesDuffy, and in that respect, the loop body indeed is not irrelevant. Commented Nov 13, 2017 at 18:30

1 Answer 1

1

[I]n case the grep returns no results, i still want it to enter the loop so i can printf something and then continue. will it work?

No. If you're piping the output of a command (i.e. grep) into the while loop, and that command produces no output at all, then read will see end-of-file on its first execution. read returns a failure code when it encounters end-of-file, which will cause the loop to terminate without its body being executed. If this were not the case then you would have an extra iteration of the while loop in every case, whether there was any data to read or not.

But you can explicitly record whether the loop body is ever executed, and afterward take appropriate action. For example:

empty=1
while read -r line: do
  empty=0
  #  ...
done < $(grep $id ${arrpre[$j]}.course)

if [ $empty -eq 1 ]; then
  # ... stuff to do in the event of empty grep output
fi
Sign up to request clarification or add additional context in comments.

5 Comments

< $(grep ...), not < <(grep ...) or <<<"$(grep ...)"? I think you're propagating an error the OP made here.
great help! tnx alot
I just copied the OP's code, @CharlesDuffy. It is probably incorrect, but that's not what the question is about.
@JohnBollinger, ...not necessarily, but I'm sure enough it's incorrect to bet my pocket change on it. :)
If you really want to execute the same code (the stuff in the loop), rather than repeating it as a separate if block, use while read -r line || [ "$empty" -eq 1 ]; do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.