0

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.

3
  • 1
    What is > ka() supposed to do? Redirections specify a filename on the right-hand side, but as read writes nothing to stdout, it doesn't makes sense to write its nonexisting output anywhere at all. Commented Jun 27, 2021 at 17:35
  • @Charles Duffy I want to append the prompt from the user to the array declared before. Commented Jun 27, 2021 at 17:36
  • 1
    Consider also printf '%s\n' "${ka[@]}" to print array elements one-per-line if you don't need to disambiguate between element boundaries and literal newlines in the data. Commented Jun 27, 2021 at 17:44

1 Answer 1

2

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[@]}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.