Bash i can't print all elements of an array but only the last one

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?

1 answer

  • answered 2018-09-21 18:57 dawg

    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