Home > database >  How do I wrap this shell command in Perl?
How do I wrap this shell command in Perl?

Time:01-03

Is there a way to wrap the following linux command into the Perl system function?

date --set="$(ssh [email protected] 'date -u')"

I have tried the following but cannot find a combination that works:

use strict;
system("date --set="$(ssh [email protected] 'date -u')"");
system, "date", "--set="$(ssh [email protected] 'date -u')"";

CodePudding user response:

You can use backticks to run a command through your shell. The backtick is an experssion that evaluates to the standard output of the command you execute.

use strict;
my $remote_date = `ssh richard\@192.168.0.4 'date -u'`;
chomp $remote_date;
system("date --set='$remote_date'");

The variable $remote_date will contain whatever ssh would print on the screen, including, possibly, login messages. The newline programs typically print at the end of every line will also be included, so I threw in a chomp.

This assumes the command ran succesfully. You can check the exit status of a program with the $? variable, but I am not sure, in your case, if this would give you the status of ssh or the remote date command you attempted to execute.

CodePudding user response:

wrap commands in Perl, with or without variables/special characters:

use strict; use warnings;
my $remote_date = system<<'EOF';
ssh [email protected] 'date -u'
EOF
chomp $remote_date;
system<<EOF;
date --set='$remote_date'
EOF

Check perldoc perlop#Quote-and-Quote-like-Operators

Especially the part about 'QuoteHereDocument'

CodePudding user response:

The problem is that you didn't escape the ", $ and @ within.

system( "date --set=\"\$( ssh richard\@192.168.0.4 'date -u' )\"" );

In this case, it's cleaner to use single-quotes on the outside, and double-quotes on the inside.

system( 'date --set="$( ssh [email protected] "date -u" )"' );
  •  Tags:  
  • perl
  • Related