gatorreina
gatorreina

Reputation: 960

How do I wrap this shell command in 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')"";

Upvotes: 4

Views: 143

Answers (3)

giusti
giusti

Reputation: 3538

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.

Upvotes: 4

ikegami
ikegami

Reputation: 385789

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" )"' );

Upvotes: 3

Gilles Quénot
Gilles Quénot

Reputation: 185116

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'

Upvotes: 2

Related Questions