Perl qx() 命令没有按预期工作

Perl qx() command not working as expected

我有一个如下所示的 perl 脚本,我想在其中使用 rsh 从 linux 机器访问远程 windows 机器上的网络路径。

$cmd = "rsh -l $username $host \"pushd \\network\path\to\the\directory && dir\"";
print $cmd, "\n";
print qx($cmd);

当我运行脚本第三行打印输出The system cannot find the path specified.但是,如果我运行第二行直接从终端打印的命令它工作正常。

我不明白为什么脚本不起作用。如果该命令在终端上有效,它也应该使用 qx() 有效。

当您通过 double-quotes 和远程 shell 对插值转义 meta-characters 时,qx 可能会再次对字符串进行插值,在这种情况下您可能需要添加另一个级别的转义。来自 the documentation of qx:

A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. ...
How that string gets evaluated is entirely subject to the command interpreter on your system. On most platforms, you will have to protect shell metacharacters if you want them treated literally. This is in practice difficult to do, as it's unclear how to escape which characters. See perlsec for a clean and safe example of a manual fork() and exec() to emulate backticks safely.