微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Bash数组保存

这个想法是,我想保存一些东西在bash中的数组。 重点是我想要一个数组的文件名称。 所以我不知道我会有多lessarrays。

#!/bin/bash declare -A NAMES index=0 for a in recursive.o timeout.o print_recursive.o recfun.o do NAMES[$index]=$a index=$((index+1)) echo ${NAMES[ $index ]} done

当我用-x运行脚本时,我可以看到NAMES [$ index],索引不是以数字表示的,所以整个事情都不起作用。

在读文件bash时将分词存储到数组中

Windows批量静态列表重命名 – 移动

如何将ls命令的输出传递给c ++中的数组

find正在运行的进程的PID并作为数组存储

数组读取问题c#

错误是在第7和第8行。交换它们,它将工作。

当index值为0时,您可以设置NAMES[0]=recursive.o ,然后递增索引并打印未设置的NAMES[1] 。 另一个元素也是一样的 因为没有输出

你的循环应该看起来像这样:

for a in recursive.o timeout.o print_recursive.o recfun.o do NAMES[$index]=$a echo ${NAMES[$index]} index=$((index+1)) done

问题在于:

declare -A NAMES

这使得一个关联数组NAMES 。 从help declare引用help declare :

Options which set attributes: -a to make NAMEs indexed arrays (if supported) -A to make NAMEs associative arrays (if supported)

你需要说:

declare -a NAMES

可能是你正在试图做到这一点:

#!/bin/bash declare -a NAMES for a in recursive.o timeout.o print_recursive.o recfun.o; do NAMES+=( "$a" ) done for (( x=0; x<${#NAMES[@]}; x++ )); do echo "Index:$x has Value:${NAMES[x]}" done

输出

Index:0 has Value:recursive.o Index:1 has Value:timeout.o Index:2 has Value:print_recursive.o Index:3 has Value:recfun.o

访问未设置的索引正在抛弃它。

NAMES[$index]=$a #Setting up an array with index 0 index=$((index+1)) #Incrementing the index to 1 echo ${NAMES[ $index ]} #Accessing value of index 1 which is not yet set

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐