pullhyphoonprotocol
pullhyphoonprotocol

Reputation: 217

Append to an array within a loop

I have this type of script, which asks for the user input and then stores it on an indexed array like:

#!/bin/bash
declare -a ka=()

for i in {1..4};
do
    read -a ka > ka();
    
done
echo ${ka[@]}

I can't manage to append the read statement to the array.

Upvotes: 0

Views: 109

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295315

When you run read -r -a arrayname, the entire array is rewritten starting from the very first item; it doesn't retain any of the prior contents.

Thus, read into a temporary array, and append that temporary array to your "real" / final one:

#!/usr/bin/env bash
case $BASH_VERSION in '') echo "ERROR: must be run with bash" >&2; exit 1;; esac

declare -a ka=()

for i in {1..4}; do
    # only do the append if the read reports success
    # note that if we're reading from a file with no newline on the last line, that last
    # line will be skipped (on UNIX, text must be terminated w/ newlines to be valid).
    read -r -a ka_suffix && ka+=( "${ka_suffix[@]}" )
done

# show current array contents unambiguously, one-per-line (echo is _very_ ambiguous)
printf ' - %q\n' "${ka[@]}"

Upvotes: 2

Related Questions