使用 bash 测试文件日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1819187/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:44:04  来源:igfitidea点击:

Test a file date with bash

bashfiledatetimecreation

提问by JeffPHP

I am trying to test how old ago a file was created (in seconds) with bash in an ifstatement. I need creation date, not modification.

我正在尝试在if语句中测试使用 bash 创建文件的时间(以秒为单位)。我需要创建日期,而不是修改。

Do you have any idea how to do this, without using a command like findwith grep?

您知道如何在不使用findwith 之类的命令的情况下执行此操作grep吗?

采纳答案by JeffPHP

Here is the best answer I found at the time being, but it's only for the modification time :

这是我目前找到的最佳答案,但仅适用于修改时间:

expr `date +%s` - `stat -c %Y /home/user/my_file`

回答by Joel

I'm afraid I cann't answer the question for creation time, but for last modification time you can use the following to get the epoch date, in seconds, since filenamewas last modified:

恐怕我无法回答创建时间的问题,但是对于上次修改时间,您可以使用以下内容获取纪元日期(以秒为单位),因为文件名上次修改的

date --utc --reference=filename +%s

So you could then so something like:

所以你可以这样:

modsecs=$(date --utc --reference=filename +%s)
nowsecs=$(date +%s)
delta=$(($nowsecs-$modsecs))
echo "File $filename was modified $delta secs ago"

if [ $delta -lt 120 ]; then
  # do something
fi

etc..

等等..

UpdateA more elgant way of doing this (again, modified time only): how do I check in bash whether a file was created more than x time ago?

更新一种更优雅的方式(同样,仅限修改时间):如何在 bash 中检查文件是否是在 x 次之前创建的?

回答by Paused until further notice.

If your system has stat:

如果您的系统有stat

modsecs=$(stat --format '%Y' filename)

And you can do the math as in Joel's answer.

您可以按照Joel的回答进行数学计算。

回答by ghostdog74

you can use ls with --full-time

您可以将 ls 与 --full-time 一起使用

file1="file1"
file2="file2"
declare -a array
i=0
ls -go --full-time "$file1" "$file2" | { while read -r  a b c d time f
do    
  time=${time%.*}  
  IFS=":"
  set -- $time
  hr=;min=;sec=
  hr=$(( hr * 3600 ))
  min=$(( min * 60 ))  
  totalsecs=$(( hr+min+sec ))
  array[$i]=$totalsecs  
  i=$((i+1))
  unset IFS      
done
echo $(( ${array[0]}-${array[1]} ))
}