简体   繁体   中英

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

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 (ie at the end or beginning) and grep that value later to decide if must be removed or kept.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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