How to delete or listing file more than x days on linux
Some time as sysadmin we need to find or remove the old files that more than x days on our Linux Server, here are some command to find or remove some old files
Step 1: Listing file ( ls )
Command syntax
find /path/to/files* -type f -mtime +5 -exec ls {} \;
Note that there are spaces between ls, {}, and \;
Explanation:
find
: the unix command for finding files/directories/links and etc./path/to/
: the directory to start your search in.-type f
: only find files.-files*
: list files that starts with files.-mtime +5
: only consider the ones with modification time older than 5 days.-exec ... \;
: for each such result found, do the following command...
.ls -- '{}'
: list the file; the{}
part is where the find result gets substituted into from the previous part.--
means end of command parameters avoid prompting error for those files starting with hyphen.
Listing the file and filter the file shown file that have modified time more than x days
Step 2: Remove file ( rm )
Command syntax
Note that there are spaces between rm, {}, and \;find /path/to/files* -type f -mtime +5 -exec rm {} \;
Be careful with special file names (spaces, quotes) when piping to rm.
There is a safe alternative - the -delete option:
find /path/to/directory/ -type f -mindepth 1 -mtime +5 -delete
That's it, no separate rm call and you don't need to worry about file names.
Replace
-delete
with -depth -print
to test this command before you run it (-delete
implies -depth
).
Alternatively, if you want to do the same for all files NEWER than five days you can running following syntax
Command syntaxfind /path/to/files* -type f -mindepth 1 -mtime -5 -exec rm {} \;
Tidak ada komentar :
Posting Komentar