这是一个简单的问题,但我无法找到答案。我有一系列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)
这告诉我访问数组包含一个尾随逗号,这是我访问数组的副作用吗?如何从值中获取逗号?我知道我可以做长度检查然后删除最后一个字符,但似乎应该有一个更明显的方法。
答案 0 :(得分:1)
您可以使用这个简单的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