I have this script

igrepy -l $1 . | while read -r line
    // some processing
echo ${tests[@]}

I've checked that 'second' has a result and it does, however my echo returns a blank string. What has gone wrong here? This is on rhel6, 'igrepy' is an alias to a case insensitive grep that only search python files

marked as duplicate by steeldriver, GAD3R, Jeff Schaller, Stephen Harris, roaima Sep 14 '16 at 22:07

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    That script fragment won't work; there's nothing before the do (eg a while or similar). – Stephen Harris Sep 14 '16 at 16:14
  • 1
    there is one, amended the op – Madden Sep 14 '16 at 16:16
  • 1
    The igrepy command is definitely returning results, and indeed after processing those results (into the 'second' var) it still has a non-empty value. Adding the declare statement returned "declare -a tests='()'", however I have put echos inside the loop and those came out too – Madden Sep 14 '16 at 16:24
  • Incidentally, any variable reference with @ must be quoted for it to work as it should. So your last line should have been echo "${tests[@]}". But that won't solve the underlying issue - see the answers from the duplicate questions for that. – roaima Sep 14 '16 at 22:09

The problem you are seeing is the standard "pipe creates subshell" with bash.

eg if you do

echo 100 | read a
echo $a

then a will still be set to 10 with bash.

In your case you have

igreppy | while read ...

and all the stuff inside that while loop will be in a subshell.

Instead it can be rewritten using process substitution

while read ...
done < <(igreppy ...)

Now no subshell is created for the while loop.

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