Strange feature in bash script

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?

2 thoughts on “Strange feature in bash script

  1. 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]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.