linux - 从 shell 脚本返回数组以在 shell 命令行中迭代/处理

标签 linux bash shell

我有一个脚本,它列出了对 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/

相关文章:

php - 为处理器网关安装 SSL 证书

arrays - 将文件捕获到数组中并在 while 循环中使用该数组

bash 别名和 awk 转义引号

linux - Shell 脚本 : Find file with the name 'error_log' and check sizes, 如果超过一定大小则删除

php - 无法从浏览器中找到 include_path 但可以在终端中使用

linux - 一个用户而不是另一个用户的Python模块导入错误

regex - Sed 正则表达式命令替换

bash - 如何使用 Bash 在两个时间戳之间的文件中搜索行

Linux RPM 安装包脚本无法更改所需文件的所有权

用于了解文件系统是否已挂载的 Shell 脚本