数组在if语句中使用时不扩展。

huangapple go评论48阅读模式
英文:

Array not expanding when using in if

问题

在这个部分,你在比较主要版本和次要版本,以排除数组中的补丁版本。但是,问题出现在“&&”之后的条件中,数组${go_sversion[$i - 1]}在循环的每个周期中都会扩展为空,即使在前一个周期中赋予了一个值。

问题可能出在数组go_sversion未在循环之前初始化。为了解决这个问题,你应该在循环之前初始化go_sversion数组,以确保它不会在每个循环迭代中重新创建。

以下是修复后的代码段:

unset go_sversion # Not allow to grow indefinitely the pool when re-execute the scripts
declare -a go_sversion  # Initialize the go_sversion array here

for i in "${!go_jversion[@]}"; do
    set -vx
    ## Create an array of the stables versions (Those versions that repeat more than or equal to 2 are stables) (second version)
    if [[ "${go_jversion[$i]}" == "${go_jversion[$i + 1]}" && "${go_sversion[$i - 1]}" != "${go_jversion[$i]}" ]]; then
        go_sversion+=("${go_jversion[$i]}")
        echo "${go_sversion[$i]}"
    fi
    set +vx
done

echo "${go_sversion[@]}"
echo "${!go_sversion[@]}"

通过在循环之前初始化go_sversion数组,你可以确保在每个循环迭代中保留数组的先前值,而不会扩展为空。

英文:

i am creating a script that will help updating the GoLang compile binary in a GNU/Linux system.

but it fail

#!/usr/bin/env bash
# -*- coding: utf-8 -*-
# set -e
# ==============================================================================
# title             : Semi Automatic Update GoLang
# description       : Script for Install, setup path, permission and update golang
# author            : Walddys Emmanuel Dorrejo Céspedes
# usage             : bash up_install.sh
# notes             : Execute this Script will ask sudo password
# dependencies      : wget awk sed curl tar
# ==============================================================================

## Get Golang Versions from repository
declare -a go_jversion go_sversion
readarray -t go_jversion < <(curl -s https://go.googlesource.com/go/+refs?format=JSON | grep -Eo "go[0-9]\.[^\"]+" | sort -V)

## Delete go_versions RC and Beta from the pool.
for i in "${!go_jversion[@]}"; do
    if [[ "${go_jversion[i]}" =~ (rc|beta) ]]; then
        unset "go_jversion[i]"
    fi
done

unset go_sversion # Not allow to grow indefinitely the pool when re-execute the scripts
for i in "${!go_jversion[@]}"; do
    set -vx
    ## Create an array of the stables versions (Those versions that repeat more than or equal to 2 are stables)
    # if [[ "${go_jversion[i]}" == "${go_jversion[i + 1]}" ]] && [[ "${go_sversion[i - 1]}" != "${go_jversion[i + 1]}" ]]; then
    #     go_sversion+=("${go_jversion[i]}")
    # fi

In this section i am comparing major version + minimum version, to exclude the patch version of the array, but the condition after the "&&", the array "${go_sversion[$i -1]}" is expanding null in each cycle of the loop, when i am assigning a value in a cycle before.

    ## Create an array of the stables versions (Those versions that repeat more than or equal to 2 are stables) (second version)
    if [[ "${go_jversion[$i]}" == "${go_jversion[$i + 1]}" && "${go_sversion[$i - 1]}" != "${go_jversion[$i]}" ]]; then
        go_sversion+=("${go_jversion[$i]}")
        echo "${!go_sversion[$i]}"
    fi
    set +vx
done

echo "${go_sversion[@]}"
echo "${!go_sversion[@]}"

My issue is in the section where "${go_sversion[$i -1]}", why is not expanding?

assign value to "${go_sversion[$i -1]}" the value display in the next cycle of the loop

答案1

得分: 5

在Bash中,允许数组是稀疏的,这意味着它们的索引不必严格连续。例如:

arr=(1 2 3)
echo "${arr[@]}" # 输出 1 2 3
echo "${!arr[@]}" # 输出 0 1 2
unset arr[1]
echo "${arr[@]}" # 输出 1 3
echo "${!arr[@]}" # 输出 0 2

当你取消设置RC和Beta值时,可能会在jversion数组中创建这种类型的间隙,但你是按顺序为sversion数组分配的。这意味着数组之间的索引不对齐。

如果你的jversion看起来像上面的数组一样,你可以将sversion[0]中的内容放入jversion[0],然后处理jversion[2]并尝试与尚不存在的sversion[1]进行匹配。

一个简单的方法来去除数组中的稀疏性是重新分配它:

go_jversion=( "${go_jversion[@]}" )

这将按顺序重新分配数组的内容,使索引不再有间隙。

如果由于某种原因这不可行,你将不得不编写能够意识到数组可能是稀疏的代码。例如,不是盲目查看go_sversion[i-1],而是查看go_sversion[-1],它将始终给你数组中的最后一个项目。

英文:

Arrays in bash are allowed to be sparse, meaning their indices are not required to be strictly sequential. For example:

arr=(1 2 3)
echo "${arr[@]}" # prints 1 2 3
echo "${!arr[@]}" # prints 0 1 2
unset arr\[1\]
echo "${arr[@]}" # prints 1 3
echo "${!arr[@]}" # prints 0 2

When you unset the RC and Beta values you could be creating these types of gaps in your jversion array, but you're assigning to the sversion array sequentially. This means the indices do not align between the arrays.

If your jversion looks like my array above, you might put something into sversion[0] from jversion[0], then process jversion[2] and attempt to match it against sversion[1] which doesn't exist yet.

One simple way to de-sparsify the array is to reassign it:

go_jversion=( "${go_jversion[@]}" )

This will reassign the contents of the array to itself in sequential order without any gaps in the indices.

If this is unviable for some reason, you'll have to write code that is aware of the possible sparseness of the array. For example, instead of blinding looking at go_sversion[i-1] you could look at go_sversion[-1] which will always give you the last item in the array.

huangapple
  • 本文由 发表于 2023年2月14日 22:05:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定