2017-01-18 22 views
0

我有一個腳本,它將調用API的列表並將響應代碼收集到一個名爲updateResponses的數組中。我看了很多帖子,推薦使用declare -p,但它不像描述的那樣工作,或者我錯誤地使用它。從shell腳本中返回一個數組,以在shell命令行中迭代/處理

我需要的是:從腳本返回數組,並通過遍歷它們來驗證元素。

script.sh包含了這個動作的亮點:

updateResponses=() 
    do 
    ..get statusCodes from list of calls in a loop... 
    updateResponses+=("$statusCode") 
    done 
declare -p updateResponses 
在我的終端

後,我執行這個腳本,我看到陣列打印出來,但它不是一個數組遍歷儘管它看起來好像它被重新初始化以供使用。運行echo "${#updateResponses[@]}"將返回0作爲大小。 script.sh後輸出的

實例完成運行時:

declare -a updateResponses='([0]="200" [1]="200" [2]="200" [3]="200" [4]="200" [5]="200" [6]="200" [7]="200" [8]="200" [9]="200" [10]="200" [11]="200" [12]="200" [13]="200" [14]="200" [15]="200" [16]="200" [17]="200" [18]="200" [19]="200" [20]="200" [21]="200" [22]="200" [23]="200" [24]="200" [25]="200" [26]="200" [27]="200" [28]="200" [29]="200" [30]="200" [31]="200" [32]="200" [33]="200")' 

回答

0

您需要運行該腳本的輸出在當前shell,例如上下文

$ . <(arr=('a b' 'c d' 'e;f') ; declare -p arr) 
$ echo ${arr[1]} 
c d 
+0

謝謝。由於我的數組已填充到腳本中,因此我添加了這個'。 <(declare -p updateResponses)'在腳本的末尾。我得到這些腳本運行在shell中的這些錯誤:'script.sh:line 59:語法錯誤附近的意外令牌'('' 'script.sh:line 59:'。<(declare -p updateResponses)'' –

+0

@OjenG:聽起來好像你沒有運行'bash'。 – choroba

+0

我的'.sh'文件正在盯着'#!/ bin/bash',所以它應該被解釋爲bash,是否正確? –