derHugo
derHugo

Reputation: 90620

Fill and read array in bash

What I actually do is getting a json string from the github api by calling

curl -u <userName> https://api.github.com/orgs/<orgName>/repos > test

I don't do it directly because in order to get jq to work, I've got to add {"result": at the beginning and } at the end of the file manually.

Now to my script in getthem

RESULT=$(cat test | jq ".result[] | .html_url");
COUNT=0
URLS=()

for line in $RESULT;
do
  echo $COUNT $line
  URLS[$COUNT]=$line
  COUNT=$(($COUNT+1))
done

#DEBUG
echo $URLS

COUNT=0
for url in $URLS;
do
  #DEBUG
  echo $COUNT $url

  #DO SOMETHING WITH RESULTS LATER
  # clone --bare $url $<onlyRepoName>.git

  COUNT=$(($COUNT+1))
done

My Problem: When I call bash ./getthem the first loop seems to work, but in the echos marked with #DEBUG there is only one line added to the array.

Here the output I get

0 "https://github.com/<orgName>/<RepoName0>"
1 "https://github.com/<orgName>/<RepoName1>"
2 "https://github.com/<orgName>/<RepoName2>"
3 "https://github.com/<orgName>/<RepoName3>"
4 "https://github.com/<orgName>/<RepoName4>"
5 "https://github.com/<orgName>/<RepoName5>"
6 "https://github.com/<orgName>/<RepoName6>"
7 "https://github.com/<orgName>/<RepoName7>"

"https://github.com/<orgName>/<repoName0>" #this should be the whole array

0 "https://github.com/<orgName>/<repoName0>" #here again it should be all 8 entries...

What am I doing wrong? Why aren't all 8 entries in the URLS array?

Upvotes: 1

Views: 474

Answers (1)

Thirupathi Thangavel
Thirupathi Thangavel

Reputation: 2465

To access all elements in the URLS array, you need to use ${URLS[@]} as below.

echo "${URLS[@]}"

COUNT=0
for url in "${URLS[@]}"
do
    # ...
done

Reference

Upvotes: 2

Related Questions