2013-08-28 225 views
0

我有一个脚本,用于将bash命令发送到负载均衡器下的多个Web服务器。我能够成功发送命令,但我也想在本地执行它。执行读取命令

#!/bin/bash 

echo "Type commands to be sent to web servers 1-8. Use ctrl+c to exit." 

function getCommand() { 
    read thisCmd 
    echo "Sending '$thisCmd'..." 
    if [ ! -z "$thisCmd" ]; then 
    # Run command locally 
    echo "From web1" 
    cd ~ 
    command $thisCmd 
    # Send to remotes 
    for i in {2..8} 
    do 
     echo "From web$i..." 
     ssh "web$i" "$thisCmd" 
    done 
    fi 
    echo Done 
    getCommand 
} 

getCommand 

但这导致

[email protected]:~$ ./sshAll.sh 
Type commands to be sent to web servers 1-8. Use ctrl+c to exit. 
cd html; pwd 
Sending 'cd html; pwd'... 
From web1 
./sshAll.sh: line 11: cd: html;: No such file or directory 
From web2... 
/home/user/html 

我如何得到这个工作?

回答

1

要扩展一个变量作为像这样的命令:

$thisCmd 

或者这

command $thisCmd 

击只会解析它作为一个单一的命令,以便;而类似的东西只会被认为是论据或其中的一部分,例如html;

所以一个基本的解决方案是使用eval:

eval "$thisCmd" 

但它是一个有点危险。它仍然与发送到远程服务器的相同。你仍然像执行eval一样执行它们。