6

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.

0

1 Answer 1

12

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.