0

I'm not able to assign all values of for in into an array so i'm able to print only the last one

   ###previouse code
    for item2 in "${!TUR[@]}"; do
        ARRAY="${item2}"
    done

    for item in "${ARRAY[@]}"; do
        printf "$ARRAY \n";
    done

How can i assign succesfully all elements to ARRAY variable and print out all elements?

lit
  • 14,456
  • 10
  • 65
  • 119
Virgula
  • 318
  • 4
  • 12
  • you’re not indexing into the array your overwriting the array and thus , the array becomes the last overwrite which is the last element in your TUR array .. – mad.meesh Sep 21 '18 at 18:44
  • Your edit isn't the proper solution, you're just appending to the first element. There's a duplicate somewhere, one sec. – Benjamin W. Sep 21 '18 at 18:51
  • Additionally, in your second loop, you want `printf '%s\n' "$item"`, not `ARRAY`. – Benjamin W. Sep 21 '18 at 18:51
  • @BenjaminW. In fact isn't the best solution i'm occuring in others troubles. – Virgula Sep 21 '18 at 18:56

1 Answers1

2

You first issue is to add elements to an array, you do something like array+=("$item_to_add")

So, you might have something like this:

tur=( A B C D )

for item in "${tur[@]}"; do
    arr+=("$item")
done
for e in "${arr[@]}"; do
    printf "%s\n" "$e";
done

BTW: It is best to avoid Bash variable names INCAPS since Bash uses these for internal use. The convention is to use lower case for user variable names.

BTW: The second loop is functionally the same as:

$ printf "%s\n" "${arr[@]}"

And both loops can be replaced with:

arr=("${tur[@]}")             # copy the array
printf "%s\n" "${arr[@]}"     # print the new array
dawg
  • 98,345
  • 23
  • 131
  • 206
  • 1
    If you expand the variable in the `printf` formatting string, its content will be interpreted as formatting directives, with potentially surprising results – I'd use `printf '%s \n' "$e"` instead (or `'%s\n'` if the space wasn't actually desired). – Benjamin W. Sep 21 '18 at 19:12
  • @BenjaminW.: Good point. Done. One could also just do `echo "$e"` in this case. – dawg Sep 21 '18 at 19:15
  • 1
    The latter loop could, of course, be replaced outright with `printf '%s\n' "${arr[@]}"`, letting `printf` repeat the format string as many times as needed to consume all arguments. – Charles Duffy Sep 21 '18 at 19:19
  • @CharlesDuffy: Ha! I was just testing that as you were typing! And the first loop can be replaced with `arr=("${tur[@]}")` – dawg Sep 21 '18 at 19:20
  • The first loop in the question used `${!TUR[@]}` indirection, though. – Benjamin W. Sep 21 '18 at 19:36