我有一个脚本,它列出了对 API 的调用并将响应代码收集到一个名为 updateResponses
的数组中。我看了很多地方并推荐了 declare -p
,但它没有按照描述的方式工作,或者我可能用错了。
我需要的:从脚本返回数组并通过遍历元素来验证元素。
我的 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")'
最佳答案
您需要在当前 shell 的上下文中运行脚本的输出,例如
$ . <(arr=('a b' 'c d' 'e;f') ; declare -p arr)
$ echo ${arr[1]}
c d
关于linux - 从 shell 脚本返回数组以在 shell 命令行中迭代/处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41714199/