LoginSignup
3
2

More than 5 years have passed since last update.

Macで更新日が3日以上前のファイルを自動削除する方法

Posted at

特定のフォルダにて、一定期間以上放置されたファイルを自動削除する方法です。cronを使って消していきます。

cronに仕込む

crontab -eでcronの設定を開き、次の行を追加します。

* * * * * find ~/Desktop/tmp/ -mtime +2 -delete && touch ~/Desktop/tmp/注意!3日以上放置されたファイルは自動削除されます

以上で~/Desktop/tmp/のファイルが毎分チェックされ、3日以上過ぎていれば削除されます。

テストコード

ファイル削除のテストコードです。

test.sh
#!/bin/bash

set -eu

: "テスト用フォルダ作成" && {
    cd ~/Desktop
    mkdir -p test
    cd test
}

: "テスト用ファイル作成" && {
    find . -delete
    for i in {0..3}
    do
        date=$(date "-v-${i}d" +'%Y%m%d%H%M')
        touch -t $date $date.log 
    done
}

: "テスト" && {
    echo 今日の日付: && date +'%Y-%m-%d %H:%M'
    echo 今あるファイル: && ls -l
    echo 更新日が3日以上過去のファイルを消す: && 
        find . -mtime +2 -name '*.log' -delete -print
    echo 残ったファイル: && ls -l
}
実行結果
今日の日付:
2017-09-13 15:27
今あるファイル:
total 0
-rw-r--r--  1 suin  staff  0 Sep 10 15:27 201709101527.log
-rw-r--r--  1 suin  staff  0 Sep 11 15:27 201709111527.log
-rw-r--r--  1 suin  staff  0 Sep 12 15:27 201709121527.log
-rw-r--r--  1 suin  staff  0 Sep 13 15:27 201709131527.log
更新日が3日以上過去のファイルを消す:
./201709101527.log
残ったファイル:
total 0
-rw-r--r--  1 suin  staff  0 Sep 11 15:27 201709111527.log
-rw-r--r--  1 suin  staff  0 Sep 12 15:27 201709121527.log
-rw-r--r--  1 suin  staff  0 Sep 13 15:27 201709131527.log

参考資料

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2