3

I have a perl script written in Server B to scp a file periodically for every hour from Server A to Server B. The problem is sometimes the scp fails for that particular hour because of some issues on the server B. I want the scp to keep retrying until it succeeds whenever this happens.

The script is:

$soc_scp=`scp -r user\@some_ip:\/home\/hbase\/hourly\/$datehr\.tar\.gz \/home\/hbase\/hourly\/$datehr\.tar\.gz`;


$echo_soc=`echo $?`;

if($echo_soc != 0)
{
$soc_scp=`scp -r user\@some_ip\:\/home\/hbase\/hourly\/$datehr\.tar\.gz \/home\/hbase\/hourly\/$datehr\.tar\.gz`;
}

I have not specified the ip for security reasons.Any help would be much appreciated.

1 Answer 1

6

Instead of the backticks, try calling scp with system(). That captures scp's exit status instead of its output. Then you can check it and retry if it was nonzero.

sleep 1 while system "scp -r user\@some_ip:/home/hbase/hourly/$datehr.tar.gz /home/hbase/hourly/$datehr.tar.gz";

This will try scp forever at 1s intervals until success.
To limit the number of tries to 10:

my $tries = 0;
while (system "scp -r user\@some_ip:/home/hbase/hourly/$datehr.tar.gz /home/hbase/hourly/$datehr.tar.gz") {
    last if $tries++ > 10;
    sleep 1;
}
7
  • $echo_soc=echo $? line actually captures the scp's exit status if am right Mar 16, 2014 at 16:01
  • Assuming scp and echo are running in the same shell. But it's not the case.
    – SzG
    Mar 16, 2014 at 16:05
  • sleep 1 waits one second. I just gave it as an example. The program will repeat attempting scp until it succeeds.
    – SzG
    Mar 16, 2014 at 16:10
  • oh, so i can state the time in seconds that the scp will wait to retry again if the command fails for the first time right?will this work if the scp fails the second time too?i mean until the exit status is zero this while loop will keep happening right? Mar 16, 2014 at 16:12
  • Yes, this will repeat to attempt scp at 1s intervals until it succeeds. If you want to limit the number of retries, you'll need a counter too.
    – SzG
    Mar 16, 2014 at 16:15

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.