5

This question already has an answer here:

This script should simply add a value to an array through a loop and then show all items of an array.

#!/bin/bash

data_file="$1"
down=()
counter=0

cat $data_file | while read line; do \
    isEven=$(( $counter % 2 ))
    if [ $isEven -eq 0 ]; then
        down+=("$line")
    fi
    (( counter ++ ))
done

echo ${down[@]}   
exit

But all I see is empty string:

host@user$ sh script.sh data_file

host@user$

The data_file contains this:

81.11
11.63
81.11
11.63
81.11
11.63
81.11
11.63 

Where's my mistake? Thanks.

marked as duplicate by Gilles bash Aug 21 '15 at 21:47

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.

10

You cannot refer variable updates made in the child process (pipe connected while block).

Instead, feed data using input redirection like this:

#!/bin/bash

data_file="$1"
down=()
counter=0

while read line; do
    isEven=$(( $counter % 2 ))
    if [ $isEven -eq 0 ]; then
        down+=("$line")
    fi
    (( counter ++ ))
done < $data_file

echo ${down[@]}   
exit

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