Today, while programming (or reprogramming) some parts of one script, I’ve noticed a strange thing.
First, the two scripts.
The working one:
#!/bin/bash let x=0 echo -e "a\nb\nc\nd" > auxfile while read LINE do [[ "${LINE}" =~ ^(a|c|d)$ ]] && AUX[$x]=${BASH_REMATCH[1]} && let x++ done < auxfile echo ${AUX[@]}
And the not working (for my purpose):
#!/bin/bash let x=0 echo -e "a\nb\nc\nd" | while read LINE do [[ "${LINE}" =~ ^(a|c|d)$ ]] && AUX[$x]=${BASH_REMATCH[1]} && let x++ done echo ${AUX[@]}
The only difference between both is just the piped while.
Someone can explain why seems to be a “reset vars” at the end of the piped while?
sub shells are evil!
Try this way.
[cc lang=”bash”]
#!/bin/bash
let x=0
while read LINE
do
[[ “${LINE}” =~ ^(a|c|d)$ ]] && AUX[$x]=${BASH_REMATCH[1]} && let x++
done< <(echo -e "a\nb\nc\nd") echo ${AUX[@]} [/cc]
This remember me a lot the nginx’s wiki page “if is evil“:
The question is why sometimes bash calls a new sub-shell and other times it works as the common way?