Arrays Bash数组保存

Arrays Bash数组保存,arrays,linux,bash,for-loop,Arrays,Linux,Bash,For Loop,我的想法是,我想在bash中将一些东西保存到一个数组中。关键是我希望一个数组有一个文件名。所以我不知道我将拥有多少阵列 #!/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运行脚本时,我可以看到名

我的想法是,我想在bash中将一些东西保存到一个数组中。关键是我希望一个数组有一个文件名。所以我不知道我将拥有多少阵列

#!/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
运行脚本时,我可以看到名称[$index],索引没有以数字表示,因此整个过程都不起作用。

问题在于:

declare -A NAMES
这将生成一个关联数组
名称
。从
帮助声明中引用

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

declare -a NAMES

错误出现在第7行和第8行。交换它们,它就会工作

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

您的循环应该如下所示:

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

可能您正在尝试这样做:

#!/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
访问未设置的索引就是将其丢弃

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

很抱歉,但这不是原因,我改变了,因为我有相同的想法,但它没有帮助。我想问题出在语法上。但是你是对的,应该是-a:)@Vrsi你试图在增加数组索引后打印值。哇,工作正常,但为什么?如果我交换这些行,那么我应该在数组[index++]中搜索,其中应该是空的。@Vrsi你怎么能期望一个没有赋值的元素包含一些东西呢?
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