0

I am wanting to pass a string variable in a ssh command. You can see in the code below I ssh to a server then cd to a directory that I pass a variable to. (cd $orig) The variable is pulled from a file that I read in and put into an array. I think that is where my error is because there might be unwanted hidden characters after I used the split command to read in from the file.

Here is the error I get:

^M: not found Can't open perl script "AddAlias.pl": No such file or directory

SSHing to

It can't find my script because the CD to the folder fails.
Sometimes the error says that 'end of file' can't be found. Like I'm doing a CD command with a EOF hidden symbol.

And here is the code:

for(my $j=0; $j < $#servName+1; $j++)
{
   print "\nSSHing to $servName[$j]\n\n";
   my $orig = $scriptfileLoc[$j];
   #my $chopped = chop($orig);
   chop($orig);
   chomp($orig);
                
   print ("\n$orig\n");

   $sshstart = `ssh $servName[$j] "cd $orig; pwd; perl AddAlias.pl $aliasName $aliasCommand $addperl            $servProfileLoc[$j]"`;

   print $sshstart;
}  

It outputs the $orig variable and it looks fine after the chop and chomp. (Which I've done both by themselves and still got the same error) So I pass it in my SSH command and it doesnt work.

This script asks the user to choose to send a file to ALL servers or just one.

  • How is `scriptfileLoc` populated? – Ted Lyngmo Oct 30 '22 at 11:35
  • Does this answer your question? [In Perl, how to remove ^M from a file?](https://stackoverflow.com/questions/650743/in-perl-how-to-remove-m-from-a-file) – stark Oct 30 '22 at 12:01
  • You preeuambly have CR LF. chop removes the last character LF. Then you chomp, which removes a trailing LF if any (by default). One solution is to use a tool such as `dos2unix` to convert the file into one that's appropriate for your OS. Another is to remove trailing whitespace e.g. using `s/\s+\z//` – ikegami Oct 31 '22 at 03:12

2 Answers2

1

To remove CR (^M) from the end of lines, use the following regex:

$orig =~ s/\r$//gm;

Anchoring at the line end guarantees that any other carriage return characters are not removed from your input. (You probably don't them there either, but to normalize line endings, it's better to not touch other characters).

g enables global matches (not only the first) and m enables multiline mode, so that $ matches the end of each line in a multiline string, not only the end of the string.

knittl
  • 246,190
  • 53
  • 318
  • 364
0

"^M" is carriage return a.k.a "\r". Use regex to remove it:

$orig =~ s/\r//g;
Narek
  • 41
  • 7