无法在变量中存储多个命令并在Bash脚本中执行

无法在变量中存储多个命令并在Bash脚本中执行,bash,variables,ssh,Bash,Variables,Ssh,我编写了一个Bash脚本,如下所示: #!/bin/bash PINGGOOGLE=echo "<H1>Ping Status</H1>";echo "<table border=\"1\">"; ping -c 3 -w 3 -q 192.168.16.129 | sed '/ping statistics/,$!d';echo "</table>" echo '<html>' >> pinghost.txt echo

我编写了一个Bash脚本,如下所示:

#!/bin/bash

PINGGOOGLE=echo "<H1>Ping Status</H1>";echo "<table border=\"1\">"; ping -c 3 -w 3 -q 192.168.16.129 | sed '/ping statistics/,$!d';echo "</table>"

echo '<html>' >> pinghost.txt
echo '<body>' >> pinghost.txt
ssh root@192.168.16.130 "${PINGGOOGLE}" >> pinghost.txt    
echo '</body>' >> pinghost.txt
echo '</html>' >> pinghost.txt
#/bin/bash
PINGGOOGLE=echo“Ping状态”;回声“;ping-c3-w3-q192.168.16.129 | sed'/ping statistics/,$!d′;回声“”
echo'>>pinghost.txt
echo'>>pinghost.txt
sshroot@192.168.16.130“${PINGGOOGLE}”>>pinghost.txt
echo'>>pinghost.txt
echo'>>pinghost.txt
但脚本显示错误

如果我在CLI中执行,输出工作正常。当我存储一个变量并通过SSH在远程机器上使用它时,问题就出现了

echo "<H1>Ping Status</H1>";echo "<table border=\"1\">"; ping -c 3 -w 3 -q 192.168.16.129 | sed '/ping statistics/,$!d';echo "</table>"
回显“Ping状态”;回声“;ping-c 3-w 3-q 192.168.16.129 | sed'/ping statistics/,$!d′;回声“”

我相信会有更好的方法,但这对我来说似乎没问题:

#!/bin/bash

PINGGOOGLE() { echo "<H1>Ping Status</H1>";echo "<table border=\"1\">"; ping -c 3 -w 3 -q 192.168.16.129 | sed '/ping statistics/,$!d';echo "</table>"; }

echo '<html>' >> pinghost.txt
echo '<body>' >> pinghost.txt
{ declare -f PINGGOOGLE; echo PINGGOOGLE; } | ssh root@192.168.16.130 >> pinghost.txt    
echo '</body>' >> pinghost.txt
echo '</html>' >> pinghost.txt
#/bin/bash
PINGGOOGLE(){echo“Ping Status;echo”“;Ping-c3-w3-q192.168.16.129 | sed'/Ping statistics/,$!d';echo”“;}
echo'>>pinghost.txt
echo'>>pinghost.txt
{declare-f PINGGOOGLE;echo PINGGOOGLE;}sshroot@192.168.16.130>>pinghost.txt
echo'>>pinghost.txt
echo'>>pinghost.txt
简而言之,不要将命令放入变量中。引用和转义存在问题。将其存储在bash函数中

然后将该函数的定义传递给remote并调用该函数

注意事项:

  • 本地别名(如果有)将通过此方法展开
  • 如果该函数使用任何本地系统变量,则它在远程系统上不可用
  • 如果该函数使用仅在本地系统上而不在远程系统上存在的任何二进制/脚本,则该函数将无法工作。(显然!)

  • 当我在脚本中使用时,我应该得到如下输出。编码MS1服务器的Ping状态---192.168.16.129 Ping统计---3个数据包传输,3个接收,0%数据包丢失,时间2001ms rtt min/avg/max/mdev=0.429/0.527/0.671/0.105 ms
    PINGGOOGLE=echo“Ping Status”
    将(尝试)执行一个名为
    Ping Status
    的命令。你想实现什么?我想把输出存储在文本文件中,就像我在我的comment@hruday你得说得更具体些。您是否正在尝试将整行分配给
    $PINGGOOGLE
    ?如果是这样的话,你需要把它弄好。但你为什么要这么做?它只在一个地方使用,而将命令存储在字符串中是非常必要的。无论如何,我现在的要求是在html表格中显示输出,我应该如何引用它,以便在脚本中使用它?