ssh 上的引号和参数替换

Quotes and parameter substitution over ssh

我试图通过 SSH 运行 执行一个命令,但我不知道如何将它正确地用引号引起来。下面是 2 次尝试,其中 none 正在做我想要的。

A) 命令用双引号括起来

version=1.1
ssh nrichard@myserver.com "
    cd /home/nrichard/${version}
    ls | while read filename ; do 
        echo $filename
        hive -f $filename &
    done"

This will be able to go to the correct directory /home/nrichard/1.1 But the while loop won't work because $filename is replaced by an empty string before the command is sent over ssh. On the other hand...

B) 命令用单引号括起来

version=1.1
ssh nrichard@myserver.com '
    cd /home/nrichard/${version}
    ls | while read filename ; do 
        echo $filename
        hive -f $filename &
    done'

This will not be able to go to the correct directory /home/nrichard/1.1. It will try to go to '/home/nrichard/${version}' which is not a directory that exists, nor the one I want to go to. But the while loop will work fine.

关于如何使这项工作有任何想法吗?

如何转义您不希望 shell 展开的变量,同时使用双引号将整个变量括起来?

version=1.1
ssh nrichard@myserver.com "
    cd /home/nrichard/${version}
    ls | while read filename ; do 
        echo $filename
        hive -f $filename &
    done"

如果您想以磁盘上的额外文件为代价摆脱任何引用问题,请试试这个。

在单独的(本地)文件中,键入要在远程主机上执行的命令。他们会使用普通引号(就像您通常在命令行上使用的那样)。

cat name_of_file_containing_commands | ssh user@host bash

将文本行管道化到 bash 会导致执行此文本(它也适用于本地,请尝试)。在这种情况下,您只需将 ssh 用作 "networked pipe".

你也可以避免没用的cat,当然:

ssh user@host bash <name_of_file_containing_commands