当前位置: 动力学知识库 > 问答 > 编程问答 >

bash - How to delete files which have X days lifetime, not last modified. Is it even possible. Linux

问题描述:

I run some kind of server on my linux machine and I use simple bash script to delete files every 3 and some files every 7 days. I use find command for doing that.But my files are saved periodically, meaning that the last modification day is the current day. So files never get deleted. Only worked for me the first time, because it met the conditions. I can't find a way to delete those files using a creation date, not modification date.

Here's my simple script:

#!/bin/sh

while true

do

java -server file.jar nogui

echo ">$(tput setaf 3)STARTING REBOOT$(tput sgr0) $(tput setaf 7)(Ctrl+C To Stop!)$(tput sgr0)"

find /folder/* -mtime +7 -exec rm -rf {} \;

find /folder/* -mtime +3 -exec rm -rf {} \;

find /logs/* -mtime +1 -exec rm -rf {} \;

echo ">Rebooting in:"

for i in 5 4 3 2 1

do

echo ">$i..."

sleep 1

done

done

If someone could help me with this, I would be really thankful!

网友答案:

No, it is not possible. Standard Linux filesystems do not track creation time at all. (ctime, sometimes mistaken for creation time, is metadata change time -- as compared to mtime, which is data modification time).


That said, there are certainly ugly hacks available. For instance, if you have the following script invoked by incron (or, less efficiently, cron) to record file creation dates:

#!/bin/bash
mkdir -p .ctimes
for f in *; do
  if [[ -f $f ]] && [[ ! -e .ctimes/$f ]]; then
    touch ".ctimes/$f"
  fi
done

...then you can look for files in the .ctimes directory that are older than three days, and delete both the markers and the files they stand for:

#!/bin/bash
find .ctimes -mtime +3 -type f -print0 | while IFS= read -r -d '' filename; do
  realname=${filename#.ctimes/}
  rm -f -- "$filename" "$realname"
done
网友答案:

If you are on ext4 Filesystem there is some hope. You can retrieve it using stat and debugfs utilities. ext4 stores creation time with inode table entry i_crtime which is 'File creation time, in seconds since the epoch' per docs. Reference Link.

网友答案:

Just an idea-don't shoot... :-)

If the files are not system files automatically generated by some process but is lets say server log files, you could possibly echo inside the file the creation date (i.e at the end or beginning) and grep that value later to decide if must be removed or kept.

分享给朋友:
您可能感兴趣的文章:
随机阅读: