【问题标题】:Bash: Array has more elements than specifiedBash:数组的元素比指定的多
【发布时间】:2016-10-27 16:28:31
【问题描述】:

我正在制作一个 shell 脚本来一次操作 n 个文件。 n 个文件存储在一个数组中。然而,在 while 循环的第一次迭代之后,数组变得大于 n。

即如果我在总共 695 个文件上运行脚本,则数组包含 100 个文件,然后在 while 循环中包含 200、300、395、295,最后是 195。

shopt -s nullglob
file_arr=(*.extension)
len_file_arr=${#file_arr[@]}
count_first=0
count_last=100

while (("$count_last" <= "$len_file_arr"))
do
        tf_array=("${file_arr[@]:${count_first}:${count_last}}")
        tf_comma_list=$(IFS=,; echo "${tf_array[@]}")
        echo ${#tf_array[@]}
        # manipulation files
        count_first=$((count_first+100))
        count_last=$((count_last+100))
        unset -v 'tf_array'
done
tf_array=("${file_arr[@]:${count_first}:${len_file_arr}}")
# manipulate left over files

我认为 unset 没有按我预期的方式运行。但是unset命令后面的数组是空的,一直没能找到解释。这种数组行为的原因是什么,我该如何解决?

【问题讨论】:

  • 您的文件名中是否嵌入了空格? (可能不是,但试图消除一个明显的问题)。祝你好运。
  • @shellter:不。它们没有空白。 CamelCase 或带有“_”以使文件名更具可读性。虽然,我认为如果有的话,引用会避免空格问题。

标签: arrays bash unset array-splice


【解决方案1】:

bash 数组切片的语法如下:

${array_name[@]:start:count}

没有

${array_name[@]:start:end}

您不应该像在这一行中那样增加 count_last:

    count_last=$((count_last+100))

并更改 while 循环条件。 要么, 改变

    tf_array=("${file_arr[@]:${count_first}:${count_last}}")

    tf_array=("${file_arr[@]:${count_first}:100}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多