Search code examples
regexbashshellperlperl-module

Use of uninitialized value $a in concatenation (.) or string


I am trying to remove the old files in a dir if the count is more than 3 over SSH

Kindly suggest how to resolve the issue.

Please refer the code snippet

#!/usr/bin/perl
use strict;
use warnings;

my $HOME="/opt/app/latest";
my $LIBS="${HOME}/libs";
my $LIBS_BACKUP_DIR="${HOME}/libs_backups";
my $a;
my $b;
my $c;
my $d;

my $command =qq(sudo /bin/su - jenkins -c "ssh username\@server 'my $a=ls ${LIBS_BACKUP_DIR} | wc -l;my $b=`$a`;if ($b > 3); { print " Found More than 3 back up files , removing older files..";my $c=ls -tr ${LIBS_BACKUP_DIR} | head -1;my $d=`$c`;print "Old file name $d";}else { print "No of back up files are less then 3 .";} '");

print "$command\n";
system($command);

output:

sudo /bin/su - jenkins -c "ssh username@server 'my ; =ls /opt/app/latest/libs_backups | wc -l;my ; =``;if ( > 3); { print " Found More than 3 back up files , removing older files..";my ; =ls -tr /opt/app/latest/libs_backups | head -1;my ; =``;print "Old file name ";}else { print "No of back up files are less then 3 .";} '"
Found: -c: line 0: unexpected EOF while looking for matching `''
Found: -c: line 1: syntax error: unexpected end of file

Solution

  • I created a new file and handling the dir check and deletion logic , scp file to remote server and executing in remote server , after completion removing the file.

    #!/usr/bin/perl
    use strict;
    use warnings;
    use File::Basename;
    use File::Path;
    use FindBin;
    use File::Copy;
    
    my $HOME="/opt/app/test/latest";
    my $LIBS_BACKUP_DIR="${HOME}/libs_backups";
    
    my $a="ls ${LIBS_BACKUP_DIR} | wc -l";
    my $b=`$a`;
    my $c="ls -tr ${LIBS_BACKUP_DIR} | head -1";
    my $d=`$c`;
    chomp($d);
    print " count : $b\n";
    
    
    
    if ($b > 3)
    {
    print " Found More than 3 back up files , removing older files..\n";
    print "Old file name $d\n";
    my $filepath="${LIBS_BACKUP_DIR}/$d";
    rmtree $filepath;
    }
    else
     {
     print "No of back up files are less then 3 .\n";
     }