-1

I wish to check whether a path given is exists or is a directory in another site server in Perl. My code is as below.

my $destination_path = "<path>";
my $ssh = "usr/bin/ssh";
my $user_id = getpwuid( $< );
my $site = "<site_name>";
my $host = "rsync.$site.com";

if ($ssh $user_id\@$host [-d $destination_path]){
  print "Is a directory.\n";
}
else{
  print "Is not a directory.\n";
}

I am sure my code is wrong as I modify the code according to bash example I see from another question but I have no clue how to fix it. Thanks for everyone that helps here.

Yih Wei
  • 537
  • 3
  • 21
  • 2
    You seem to have forgotten to mention what the problem is. What unexpected behaviour are you seeing? Is it as simple having `usr/bin/ssh` where I suspect you want `/usr/bin/ssh`? – Dave Cross Dec 19 '18 at 08:32
  • Hi. @DaveCross The problem of my code is not working for checking whether the directory exists or not in the remote server. – Yih Wei Dec 19 '18 at 08:45

2 Answers2

3

[ is the name of a command, and it must be separated from other words on the command line. So just use more spaces:

$ssh $user\@$host [ -d $destination_path ]

To actually execute this command, you'll want to use the builtin system function. system returns 0 when the command it executes is successful (see the docs at the link)

if (0 == system("$ssh $user\@$host [ -d $destination_path ]")) {
    print "Is a directory.\n";
} else {
    print "Is not a directory.\n";
}
mob
  • 117,087
  • 18
  • 149
  • 283
  • Hi. Thanks for your answer. The answer is working. May I ask how can I create directory for the path if it is not a directory? I have tried `system("$ssh $user\@$host [ mkdir -p $destination_path ]")` but it don't seem to be working. – Yih Wei Dec 19 '18 at 08:44
1

Accessing the remote file system through SFTP:

use Net::SFTP::Foreign;

$sftp = Net::SFTP::Foreign->new("rsync.$site.com");
if ($sftp->test_d($destination_path)) {
    "print $destination_path is a directory!\n";
}
salva
  • 9,943
  • 4
  • 29
  • 57