Search code examples
perlterminalremote-connectionrshqx

Perl qx() command not working as expected


I have a perl script as below, where I want to access a network path on a remote windows machine from a linux machine using rsh.

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

When I run the script the third line prints output The system cannot find the path specified. However, if I run the command printed by the second line directly from the terminal it works fine.

I'm not able to understand why the script is not working. If the command works from the terminal, it should work using qx() too.


Solution

  • While you escape your meta-characters against interpolation by double-quotes and by the remote shell, qx might itself interpolate the string again, in which case you might need to add another level of escaping. From 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.