remote shell call with awk from perl script

684 Views Asked by At

I'm trying to execute commands on a remote host from a perl script.

$check = `rsh host1 "df -k /backup/|tail -1|awk \'{print \$5}\'"`;
print $check

But awk returns me the whole string instead of one column.

/dev/md/dsk/d10      4133838 1936684 2155816    48%    /

I need only

48%

Looks like there is an issue in escaping but don't know what exactly wrong. Please help.

1

There are 1 best solutions below

1
On BEST ANSWER

One option would be to use qx with the single quote as a delimiter instead, so that Perl variables are not interpolated:

$check = qx'rsh host1 "df -k /backup/|tail -1|awk \"{print \$5}\""';

I have used double quotes around the awk command, so it is still necessary to escape the $5 to prevent it from being interpreted as a shell variable.

If you are happy to run tail and awk on the local machine, you can remove the double quotes:

$check = qx'rsh host1 df -k /backup/|tail -1|awk "{print \$5}"';

This results in more data being copied back from the remote machine, which may or may not be a problem.

Alternatively, you could split the output using Perl and avoid the problem entirely:

$check = (split /\s+/, qx'rsh host1 "df -k /backup/|tail -1"')[4];