[英]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. 我正在通过perl脚本执行unix命令来获取目录的大小。
$path = "/dir1/di2/";
system("du -sh $path");
How can I get the result back in my perl script. 如何将结果返回到我的perl脚本中。
I am using 我在用
$size = system("du -sh $path");
print $size
But it is giving size=0; 但是它给size = 0;
You could also do this using perl
, eg as shown here . 您也可以使用
perl
进行此操作,例如,如此处所示 。 Something like 就像是
use File::Find;
find(sub { $size += -s if -f $_ }, $path);
Perl syntax is very similar to Bash one. Perl的语法与Bash的语法非常相似。 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 (~).
在美国版式上,它与代字号(〜)相同。
a system
call returns the status of the call, not the output. system
调用返回调用的状态,而不是输出。 Use backticks (or the qx
operator) like: 使用反引号(或
qx
运算符),例如:
$size = qx(du -sh $path);
It's returning the command status, which is success. 它返回命令状态,即成功。
Instead, do: 相反,请执行以下操作:
$size = `du -sh $path`
(backquotes delimiting command) (反引号分隔命令)
Or you may redirect the output to a file handle and use it to get the output. 或者,您可以将输出重定向到文件句柄,然后使用它来获取输出。
open (FD,"du -hs \"$path\" |");
while (<FD>) {
...
}
#!/bin/perl
$path = "/dir1/di2/";
print(qx(du -sh $path));
This should work ! 这应该工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.