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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With