2017-06-12 85 views
1

我其實做的就是通過調用Fill和在bash閱讀陣列

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

正從GitHub的API JSON字符串我千萬不要因爲爲了得到JQ的工作,我已經直接做必須手動在文件末尾添加{"result":並在文件末尾添加}

現在給我的腳本在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 

我的問題: 當我打電話bash ./getthem第一循環似乎工作,但在標有#調試上的回波也只加了一行到陣列。

這裏的輸出我得到

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... 

我在做什麼錯?爲什麼不是URLS數組中的所有8個條目?

+0

'./getthem:8號線:在的SyntaxError意外字»(« ./getthem:8號線:URLS + =($線)」 ' – derHugo

+0

就會明白:沒有空格!'URLS + =($ line)'...導致與我的問題相同的輸出,雖然 – derHugo

+0

做到了..現在我的輸出只有前8行 – derHugo

回答

2

要訪問URLS陣列中的所有元素,您需要按如下所示使用${URLS[@]}

echo "${URLS[@]}" 

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

Reference

+1

很棒這個做到了! 我猜這是關於指針和值的東西? – derHugo

+1

可以改進這個答案的多種方式1)無用的'cat' 2)避免反模式將文件轉儲到變量中d)在文件中使用輸入重定向)3)不加引號的變量擴展('在$ RESULT'中的行可能發生分詞)4)未加引號的數組擴展('for url in $ {URLS [@]}'再次)5)一般的做法,雙引號變量 – Inian

+0

謝謝@Inian,我已經更新:) –