Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Bash array without trailing commas

Tags:

bash

This is a simple question but I couldn't find the answer to it. I've got an array of IPs that I want to distribute a file to and don't want to execute separate scp commands each time. I designed this bash function to do this for me:

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
}

Which spits out

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
[email protected]'s password: 
script.sh                                                                                                                                                              
100%  326     0.3KB/s   00:00    
Transferred script.sh to /usr/bin on target at 200.150.100.4

Wheras I wanted

hello, loopControl is 0, targetValue is 200.150.100.2
[email protected]'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)

Which shows me that accessing the array includes a trailing comma, is this a side effect of how I'm accessing the array? How can I get the commas out of the values? I'm aware I could do length checks and then just remove the last character, but it seems like there should be a more obvious way.

like image 970
Michael Hackman Avatar asked Sep 17 '25 10:09

Michael Hackman


1 Answers

You can trim all commas , with this simple bash parameter expansion :

$ 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
like image 139
Gilles Quenot Avatar answered Sep 20 '25 03:09

Gilles Quenot