Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wrap this shell command in Perl?

Tags:

perl

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')"";
like image 264
gatorreina Avatar asked Sep 10 '25 18:09

gatorreina


2 Answers

You can use backticks to run a command through your shell. The backtick is an expression 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 successfully. 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.

like image 190
giusti Avatar answered Sep 14 '25 12:09

giusti


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" )"' );
like image 32
ikegami Avatar answered Sep 14 '25 11:09

ikegami