Scott M
Scott M

Reputation: 119

Different results with shell command in and out of a perl script

I have a perl script that needs to check for an empty directory on a remote machine. Using ksh I can get the following shell script to work:

ksh# ssh user@host '[ "$(ls -A /empty/dir/* 2>/dev/null)" ] && echo "1" || echo "0"'

This correctly returns a "0" if the directory is empty or does not exist. It returns a "1" only if the directory contains something.

When I place this line inside of the perl script though like so:

#!/usr/bin/perl
print `ssh user\@host '[ "$(ls -A /empty/dir/* 2>/dev/null)" ] && echo "1" || echo "0"'`

No matter what I put in there it returns a "1", empty directory or not. I've checked env values compared to the normal shell and the perl script and they are the same.

Does anyone have any ideas why this command would return different results only in the perl script?

Both machines are AIX 6.1 with KSH as the default shell.

Upvotes: 3

Views: 637

Answers (2)

salva
salva

Reputation: 10234

use Net::SFTP::Foreign;

my $s = Net::SFTP::Foreign->new('user@host');
my $empty = 1;
if (my $d = $s->opendir('/empty/dir')) {
  if (defined $s->readdir($d)) {
    $empty = 0
  }
}

Upvotes: 0

mob
mob

Reputation: 118595

Text inside backticks is interpolated as if it were inside double quotes before being passed to the OS. Run

print qq`ssh user\@host '[ "$(ls -A /empty/dir/* 2>/dev/null)" ] && echo "1" || echo "0"'`

to see exactly what string is getting passed to the OS. I'll bet you'll at least have to escape the $.

A safer and saner way is to build your command first and run it inside backticks later:

# q{...} does no interpolation
my $cmd = q{ssh user\@host '[ "$(ls -A /empty/dir/* 2>/dev/null)" ] && echo "1" || echo "0"'};
print `$cmd`;

Upvotes: 2

Related Questions