【问题标题】:Bash array savingBash 数组保存
【发布时间】:2014-04-30 01:31:35
【问题描述】:

我想在 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 运行脚本时,我可以看到 NAMES[$index],索引没有以数字表示,所以整个事情都不起作用。

【问题讨论】:

    标签: arrays linux bash for-loop


    【解决方案1】:

    错误出现在第 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
    

    【讨论】:

    • 哇,工作,但为什么?如果我交换行 i 比我应该是 priting array [index++] where应该什么都没有。
    • @Vrsi 你怎么能期望一个没有被赋值的元素包含一些东西?
    【解决方案2】:

    也许你正在尝试这样做:

    #!/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
    

    【讨论】:

      【解决方案3】:

      问题出在以下几点:

      declare -A NAMES
      

      这会产生一个关联数组NAMES。引用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
      

      【讨论】:

      • 很抱歉,但这不是原因,我改变了这一点,因为我有同样的想法,但它没有帮助。我认为问题出在语法上。但你说得对,应该有 -a :)
      • @Vrsi 您正在尝试在增加数组索引后打印该值。
      猜你喜欢
      • 2012-07-27
      • 2014-03-28
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 2018-11-13
      • 2016-07-22
      相关资源
      最近更新 更多