出于练习原因,我尝试以下脚本:
#!/bin/bash
NUM_OF_SERVERS=(server1 server2)
SSH_USERNAME=root
SSH_PASSWORD=password
version=$(cat /etc/redhat-release)
for HOST in ${NUM_OF_SERVERS[@]};
do /usr/bin/sshpass -p $SSH_PASSWORD ssh $SSH_USERNAME@$HOST echo "$version"
echo "The software version for ${NUM_OF_SERVERS[0]} is $version"
echo "The software version for ${NUM_OF_SERVERS[1]} is $version"
done
和输出:
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `echo CentOS Linux release 7.4.1708 (Core) '
The software version for server1 is CentOS Linux release 7.4.1708 (Core)
The software version for server2 is CentOS Linux release 7.4.1708 (Core)
The software version for server1 is CentOS Linux release 7.4.1708 (Core)
The software version for server2 is CentOS Linux release 7.4.1708 (Core)
为什么会出现此语法错误以及为什么循环发生4次而不是2?
任何帮助都将不胜感激。
答案 0 :(得分:0)
此循环仅运行数组时间的成员数。 由于2个回声,它看起来可能会运行更多次。
我相信你应该更多地关注身份。
for HOST in ${NUM_OF_SERVERS[@]};
do /usr/bin/sshpass -p $SSH_PASSWORD ssh $SSH_USERNAME@$HOST echo "$version"
echo "The software version for ${NUM_OF_SERVERS[0]} is $version"
echo "The software version for ${NUM_OF_SERVERS[1]} is $version"
done
如果您真的想要打印有关版本的信息,还有其他问题。
for HOST in ${NUM_OF_SERVERS[@]}; do
v=`/usr/bin/sshpass -p $SSH_PASSWORD ssh $SSH_USERNAME@$HOST "uname -a"`
echo "The software version for $HOST is $v"
done
因为两个回波完全独立于循环迭代的当前值。