Linux上で〇日前のファイルを削除

コマンドラインで一発 (20日前のファイルを削除)

# find /var/log/test/ -mtime +20 -name "test_log*" -delete

テスト(20日前が2023年の大晦日だとする)

# mkdir /var/log/test
# touch /var/log/test/test_log-aaa
# touch -t 202312310000 /var/log/test/test_log-bbb
# mkdir /var/log/test/testdir
# touch /var/log/test/testdir/test_log-ccc
# touch -t 202312310000 /var/log/test/testdir/test_log-ddd
# find /var/log/test/ -mtime +20 -name "test_log*"
/var/log/test/test_log-bbb ← 大晦日の日付のファイル
/var/log/test/testdir/test_log-ddd ← 大晦日の日付のファイル
# ll /var/log/test/
total 0
drwxr-xr-x 2 root root 46 Jan 21 22:06 testdir
-rw-r--r-- 1 root root  0 Jan 21 21:54 test_log-aaa
-rw-r--r-- 1 root root  0 Dec 31 00:00 test_log-bbb
# ll /var/log/test/testdir/
total 0
-rw-r--r-- 1 root root 0 Jan 21 22:06 test_log-ccc
-rw-r--r-- 1 root root 0 Dec 31 00:00 test_log-ddd

# find /var/log/test/ -mtime +20 -name "test_log*" -delete

# ll /var/log/test/
total 0
drwxr-xr-x 2 root root 26 Jan 21 22:08 testdir
-rw-r--r-- 1 root root  0 Jan 21 21:54 test_log-aaa
# ll /var/log/test/testdir/
total 0
-rw-r--r-- 1 root root 0 Jan 21 22:06 test_log-ccc