Birbal
Birbal

Reputation: 353

Bash append values to a list inside a for loop

I have the following bash script sequence:

blocks=()

for line in ${fail_no[@]}
do
  new_line=`sed "$line!d" $1`
  command=`echo $new_line | cut -d ',' -f2`
  while [[ $new_line != *"$PROJ_NAME"* ]] 
  do
    line=$((line-1))
    new_line=`sed "$line!d" $1`
  done
  curr_block=`echo $new_line | cut -d ',' -f1`
  echo $curr_block
  blocks+=("$curr_block")
done

echo $blocks

Please ignore the details but I just want to add all the values of curr_block into the list blocks. When I run this script I have 2 values for curr_block but the block variable at the end contains only the value of the first curr_block and not the second one (or the one after that if is the case). I have been looking at this for 1h and I can't see where is the problem.

Upvotes: 1

Views: 7929

Answers (2)

chepner
chepner

Reputation: 531165

I would use something like this:

readarray -t blocks < <(
  awk -F, -v pname "$PROJ_NAME" '
      BEGIN { fail=('"${fail_no[*]}"'); }
      $0 ~ pname {block=$1};
      NR in fail { print $block; }
      ' "$1")

The single awk process goes through the file line by line, always remembering what the current value of block will be, should it encounter a line that matches one listed in fail_no. When it does, output that block. The output of awk is then collected in the desired array.

Upvotes: 2

Robert Seaman
Robert Seaman

Reputation: 2582

blocks is an array. Using echo $blocks will print the first element (as you are seeing).

The correct way to print all elements of an array is as follows:

echo "${blocks[@]}"

Upvotes: 4

Related Questions