AnonGeek
AnonGeek

Reputation: 7938

Get value of execution of a unix command in perl script

I am executing a unix command through perl script to get size of a direcory.

$path = "/dir1/di2/";
system("du -sh $path");

How can I get the result back in my perl script.

I am using

$size = system("du -sh $path");
print $size

But it is giving size=0;

Upvotes: 0

Views: 8538

Answers (6)

Sumukh Bhandarkar
Sumukh Bhandarkar

Reputation: 384

#!/bin/perl
$path = "/dir1/di2/";
print(qx(du -sh $path));

This should work !

Upvotes: 0

techiewickie
techiewickie

Reputation: 11

Or you may redirect the output to a file handle and use it to get the output.

open (FD,"du -hs \"$path\" |");
while (<FD>) {
...
}

Upvotes: 1

Zagorax
Zagorax

Reputation: 11890

Perl syntax is very similar to Bash one. Backquote your command and it's output will be stored in the variable.

    my $variable = `command`;
    print $variable;

If your command has output on multiple lines, you can assign it to an array, for example:

    my @files = `ls -l`
    chomp @files;

Then, every output line will be stored in a different element of the array.

How to do a backquote may vary depending on your keyboard layout. On US layout it's the same key of tilde (~).

Upvotes: 3

djconnel
djconnel

Reputation: 431

It's returning the command status, which is success.

Instead, do:

$size = `du -sh $path`

(backquotes delimiting command)

Upvotes: 1

Thor
Thor

Reputation: 47099

You could also do this using perl, e.g. as shown here. Something like

use File::Find;           
find(sub { $size += -s if -f $_ }, $path);

Upvotes: 5

JRFerguson
JRFerguson

Reputation: 7516

a system call returns the status of the call, not the output. Use backticks (or the qx operator) like:

$size = qx(du -sh $path);

Upvotes: 1

Related Questions