使用 Bash 获取特定文件的 mtime?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4774358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get mtime of specific file using Bash?
提问by Industrial
I am well aware of being able to do find myfile.txt -mtime +5
to check if my file is older than 5 days or not. However I would like to fetch mtime in days of myfile.txt and store it into a variable for further usage. How would I do that?
我很清楚能够find myfile.txt -mtime +5
检查我的文件是否超过 5 天。但是,我想以 myfile.txt 的天数获取 mtime 并将其存储到变量中以供进一步使用。我该怎么做?
回答by T.J. Crowder
stat
can give you that info:
stat
可以给你这些信息:
filemtime=`stat -c %Y myfile.txt`
%Y
gives you the last modification as "seconds since The Epoch", but there are lots of other options; more info. So if the file was modified on 2011-01-22 at 15:30 GMT, the above would return a number in the region of 1295710237.
%Y
为您提供“自大纪元以来的秒数”的最后修改,但还有很多其他选项;更多信息。因此,如果文件在 2011 年 1 月 22 日格林威治标准时间 15:30 被修改,则上述内容将返回 1295710237 区域内的数字。
Edit: Ah, you want the time in days since it was modified. That's going to be more complicated, not least because a "day" is not a fixed period of time (some "days" have only 23 hours, others 25 — thanks to daylight savings time).
编辑:啊,您想要自修改以来的天数。这将变得更加复杂,尤其是因为“一天”不是固定的时间段(有些“天”只有 23 小时,有些则有 25 小时——这要归功于夏令时)。
The naiveversion might look like this:
在天真的版本可能是这样的:
filemtime=`stat -c %Y `
currtime=`date +%s`
diff=$(( (currtime - filemtime) / 86400 ))
echo $diff
...but again, that's assuming a day is always exactly 86,400 second long.
...但同样,这是假设一天总是正好 86,400 秒长。
More about arithmetic in bash here.
更多关于 bash 中的算术在这里。
回答by mob
AGE=$(perl -e 'print -M $ARGV[0]' $file)
will set $AGE to the age of $file in days, as Perl's -M
operator handles the stat
call and the conversion to days for you.
将 $AGE 设置为 $file 的天数,因为 Perl 的-M
操作员会stat
为您处理调用和转换为天。
The return value is a floating-point value (e.g., 6.62849537 days). Add an int
to the expression if you need to have an integer result
返回值是一个浮点值(例如,6.62849537 天)。int
如果需要整数结果,请在表达式中添加一个
AGE=$(perl -e 'print int -M $ARGV[0]' $file)
Ruby and Python also have their one-liners to stat a file and return some data, but I believe Perl has the most concise way.
Ruby 和 Python 也有它们的单行程序来统计文件并返回一些数据,但我相信 Perl 有最简洁的方式。
回答by silvio
I this the answer?
我这是答案?
A=$(stat -c "%y" myfile.txt)
look at stat-help
看看统计帮助
stat --help
Usage: stat [OPTION]... FILE...
Display file or file system status.
[...]
-c --format=FORMAT use the specified FORMAT instead of the default;
output a newline after each use of FORMAT
[...]
The valid format sequences for files
[...]
%y Time of last modification, human-readable
%Y Time of last modification, seconds since Epoch
[...]