这是一个简单的问题,但我找不到答案。我有一系列的IP,我想将文件分配到,并且不想每次执行单独的SCP命令。我为我设计了这个狂欢功能:
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)
表明我访问数组包括一个尾随逗号,这是我如何访问数组的副作用吗?如何从值中获得逗号?我知道我可以进行长度检查,然后删除最后一个字符,但似乎应该有更明显的方法。
您可以使用此简单 bash参数扩展:
来修剪所有逗号,
$ declare -a targets=("200.150.100.2", "200.150.100.3", "200.150.100.4")
$ new_targets="${targets[@]%,}"
$ printf '%sn' "${new_targets[@]}"
200.150.100.2 200.150.100.3 200.150.100.4