how do I check in bash whether a file was created more than x time ago?

后端 未结 8 1237
时光说笑
时光说笑 2020-12-22 18:24

I want to check in linux bash whether a file was created more than x time ago.

let\'s say the file is called text.txt and the time is 2 hours.

 if [         


        
8条回答
  •  鱼传尺愫
    2020-12-22 19:18

    Using the stat to figure out the last modification date of the file, date to figure out the current time and a liberal use of bashisms, one can do the test that you want based on the file's last modification time1.

    if [ "$(( $(date +"%s") - $(stat -c "%Y" $somefile) ))" -gt "7200" ]; then
       echo "$somefile is older then 2 hours"
    fi
    

    While the code is a bit less readable then the find approach, I think its a better approach then running find to look at a file you already "found". Also, date manipulation is fun ;-)


    1. As Phil correctly noted creation time is not recorded, but use %Z instead of %Y below to get "change time" which may be what you want.

    [Update]

    For mac users, use stat -f "%m" $somefile instead of the Linux specific syntax above

提交回复
热议问题