Search code examples
bashgitlabgitlab-api

How to avoid the storing values without spacing in an array?


In my shell script I have wrote to store the values of a command in an array. It has two elements (712,710), but they are stored in the array as one element (without spacing).How do I avoid that?

My script:

 #! /bin/bash

GIT_API="https://XXXXXXXXXX.lk/api/v4"
GIT_TOKEN="XXXXXXXXXXXX"
GROUP_NAME="testdevops"

GROUP_ID=$(curl --request GET --header "PRIVATE-TOKEN: $GIT_TOKEN" -g "$GIT_API/groups?top_level_only=true&search=testdevops" | jq -r ".[] .id")
echo "${GROUP_ID}"

USER_ID_ARRAY=($(curl --request GET --header "PRIVATE-TOKEN: $GIT_TOKEN" "$GIT_API/groups/$GROUP_ID/members" | jq -r ".[] .id"))

USER_ACCESS_LEVEL_ARRAY=($(curl --request GET --header "PRIVATE-TOKEN: $GIT_TOKEN" "$GIT_API/groups/$GROUP_ID/members" | jq -r ".[] .access_level"))    
         
echo ${USER_ID_ARRAY[*]}
         
echo ${USER_ACCESS_LEVEL_ARRAY[*]}

for (( c=0; c<${#USER_ACCESS_LEVEL_ARRAY[@]}; c++ ))
do    
        if [ ${USER_ACCESS_LEVEL_ARRAY[$c]} != 50 ]
        then
        NON_OWNER_USERS_ARRAY_ELEMENT_NO+=(${c})
        fi
done
    
echo ${NON_OWNER_USERS_ARRAY_ELEMENT_NO[*]}
    
for (( d=0; d<${#NON_OWNER_USERS_ARRAY_ELEMENT_NO[@]}; d++ ))
do
        NON_OWNER_USERS_ID_ARRAY+=${USER_ID_ARRAY[${NON_OWNER_USERS_ARRAY_ELEMENT_NO[$d]}]}
done

echo ${NON_OWNER_USERS_ID_ARRAY[0]}

Actual Output:

36 711 712 710
50 50 20 10
2 3
712710

Output Need:

36 711 712 710
50 50 20 10
2 3
712 710

The Scenario is this: Identify the users for given group name in the GitLab and remove them from the group.


Solution

  • Add elements with (), access them with the @

    as follows:

    # declare
    myArry=()
    
    for(( d=0; d<2; d++ ))
    do 
       # add element with ()
       myArray+=($d)
    done
    
    # access elemets with the @ operator
    for value in "${myArray[@]}" 
    do  
        echo "$value"
    done
    
    # or access the first element
    echo ${myArray[0]}