不带尾随逗号访问Bash数组

不带尾随逗号访问Bash数组,bash,Bash,这是一个简单的问题,但我找不到答案。我有一个IP阵列,我想将文件分发给它,但不想每次都执行单独的scp命令。我设计这个bash函数就是为了实现这一点: function scp_Targets () { loopControl=0 declare -a targets=("200.150.100.2", "200.150.100.3", "200.150.100.4") arraySize=${#targets[@]} while [ $loopControl

这是一个简单的问题,但我找不到答案。我有一个IP阵列,我想将文件分发给它,但不想每次都执行单独的scp命令。我设计这个bash函数就是为了实现这一点:

function scp_Targets () {
    loopControl=0
    declare -a targets=("200.150.100.2", "200.150.100.3", "200.150.100.4")
    arraySize=${#targets[@]}

    while [ $loopControl -lt $arraySize ]
    do
        echo "hello, loopControl is $loopControl, targetValue is ${targets[$loopControl]}"
        scp $1 root@${targets[$loopControl]}:$2
        if [ $? -eq 0 ]
        then
                echo "Transferred $1 to $2 on target at ${targets[$loopControl]}"
        fi
        ((loopControl++))
    done
}
吐出来的

hello, loopControl is 0, targetValue is 200.150.100.2,
ssh: Could not resolve hostname 200.150.100.2,: Name or service not known
lost connection
hello, loopControl is 1, targetValue is 200.150.100.3,
ssh: Could not resolve hostname 200.150.100.3,: Name or service not known
lost connection
hello, loopControl is 2, targetValue is 200.150.100.4
root@200.150.100.4's password: 
script.sh                                                                                                                                                              
100%  326     0.3KB/s   00:00    
Transferred script.sh to /usr/bin on target at 200.150.100.4
我想要什么

hello, loopControl is 0, targetValue is 200.150.100.2
root@200.150.100.2's password: 
script.sh                                                                                                                                                              
100%  326     0.3KB/s   00:00    
Transferred script.sh to /usr/bin on target at 200.150.100.2
... (same for the other two IPs)

这表明访问数组时包含一个尾随逗号,这是访问数组时的副作用吗?如何从值中提取逗号?我知道我可以进行长度检查,然后删除最后一个字符,但似乎应该有一种更明显的方法。

您可以使用以下简单的方法修剪所有逗号


declare-a targets=(“200.150.100.2”“200.150.100.3”“200.150.100.4”)
这里不应该有逗号就是这样,太简单了!谢谢,自动检测到这一点issue@thatotherguy很棒的资源,谢谢你的提示!但一开始不写逗号更简单,不是吗?当然@Barmar:)
$ declare -a targets=("200.150.100.2", "200.150.100.3", "200.150.100.4")
$ new_targets="${targets[@]%,}"
$ printf '%s\n' "${new_targets[@]}"
200.150.100.2 200.150.100.3 200.150.100.4