Reputation: 7938
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
Reputation: 384
#!/bin/perl
$path = "/dir1/di2/";
print(qx(du -sh $path));
This should work !
Upvotes: 0
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
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
Reputation: 431
It's returning the command status, which is success.
Instead, do:
$size = `du -sh $path`
(backquotes delimiting command)
Upvotes: 1
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
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