简体   繁体   English

从shell命令捕获输出,而无需[也]将其输出发送到stdout

[英]Capturing output from a shell command without [also] sending its output to stdout

I am writing a Perl program to get the modified time of a particular file. 我正在编写一个Perl程序来获取特定文件的修改时间。 I have tried the following scenarios: 我尝试了以下方案:

  1. $time = system("stat -c %y temp.txt") --> this sets $time to "0" and writes "2013-04-03 06:10:02.000000000 -0600" to stdout. $time = system("stat -c %y temp.txt") ->将$ time设置为“ 0”,并将“ 2013-04-03 06:10:02.000000000 -0600”写入标准输出。

  2. $time = `stat -c %y temp.txt` --> this sets $time to "2013-04-03 06:10:02.000000000 -0600" and also displays the same thing ("2013-04-03 06:10:02.000000000 -0600") on stdout. $time = `stat -c %y temp.txt` >这会将$ time设置为“ 2013-04-03 06:10:02.000000000 -0600”,并且还会显示相同的内容(“ 2013-04-03 06: 10:02.000000000 -0600“)在标准输出上。

  3. $time = exec("stat -c %y temp.txt") --> this does not set $time but prints "2013-04-03 06:10:02.000000000 -0600" on stdout. $time = exec("stat -c %y temp.txt") ->这不会设置$ time,而是在stdout上显示“ 2013-04-03 06:10:02.000000000 -0600”。

As this is flooding my stdout with the same type of data again and again, I want to get rid of it. 因为这一次又一次地用相同类型的数据淹没我的标准输出,所以我想摆脱它。 Can please somebody help me in this? 请问有人可以帮我吗?

You'd be better off using perl's built-in stat function: 您最好使用perl的内置stat函数:

@st = stat('temp.txt');

$st[9] now contains the Unix epoch timestamp for the last-modified time. $st[9]现在包含上次修改时间的Unix纪元时间戳。 You could get it into a more useful format like this 您可以将其转换为更有用的格式,例如

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($st[9]);

or just get a printable string like this 或只是得到这样的可打印字符串

$time = localtime($st[9]);

Backticks (and the related qx operator or readpipe function) do not write any output on standard output; 反引号(以及相关的qx运算符或readpipe函数)不会在标准输出上写入任何输出。 they execute a command, capture the command's output and return it (usually to assign it to some variable). 他们执行命令,捕获命令的输出并返回(通常将其分配给某个变量)。 So 所以

$time = `stat -c %y temp.txt`

will set $time and not write anything to standard output. 将设置$time并且不向标准输出写入任何内容。 It is possible for the command to write something to standard error, but from the symptoms you describe, it doesn't look like that is what's happening. 该命令可能会向标准错误中写入内容,但是从您描述的症状来看,这似乎并不是正在发生的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM