在单引号和双引号层内引用 {print $NF}?

quoting {print $NF} inside layers of single and double quotes?

一直在尝试弄清楚如何在双引号内使用单引号进行单引号。这就是我想要做的....

我想从 perl 运行 一个系统命令... - 对远程机器执行 ssh - 执行 'uptime' 然后从中提取最后一个字段(平均负载最后 15 分钟)。

\#\!/usr/bin/env perl   
my $cmd = "ssh othermachine 'uptime | awk '{print $NF}'' > local_file.dat";   
system($cmd);

当然不会 运行 ...

% ./try.pl

Missing }.
%

缺少“}”???看起来它正在将 $NF} 解释为 var?我尝试转义 {} 字符但没有成功。我试着逃避 $,没有运气。我在 } 之前尝试了 space,没有运气,但有不同的 msg(未定义变量)。

c-shell 顺便说一句,提前致谢!

您希望以下内容成为 ssh 的第二个参数:

uptime | awk '{print $NF}'

为此,您只需在其周围加上单引号。但这不起作用,因为它包含单引号。


您想构建一个包含 $NF 的字符串,但您是按如下方式进行的:

"...$NF..."

这会将(不存在的)Perl 变量 $NF 的值放入字符串中。


一步一步来。

  • 静态:

    1. 远程命令:

       uptime | awk '{print $NF}'
      
    2. 本地命令:

      ssh othermachine 'uptime | awk '\''{print $NF}'\''' >local_file.dat
      
    3. 字符串文字:

      my $local_cmd = q{ssh othermachine 'uptime | awk '\''{print $NF}'\''' >local_file.dat}
      
  • 动态:

    use String::ShellQuote qw( shell_quote );
    
    my $remote_cmd = q{uptime | awk '{print $NF}'};
    my $local_cmd = shell_quote('ssh', 'othermachine', $remote_cmd) . ' >local_file.dat';
    

使用 Net::OpenSSH 并让它为您报价:

use Net::OpenSSH;

my $ssh = Net::OpenSSH->new($othermachine,
                            remote_shell => 'tcsh');
$ssh->system({stdout_file => 'local_file.dat'},
             'uptime', \'|', 'awk', '{print $NF}')
  or die "ssh command failed: " . $ssh->error;