This time, if you build a CCTV system with Raspberry PI, create a command and register it in Cron to automatically delete image files and video files that have passed a certain period of time.
The following command will display files that are older than one day. Current date: 2020/09/29 Get files older than one day: Specify the argument "+1". Get the file for 28 days: Specify the argument from "+1" to "0".
■ Command
find /var/lib/motion -name '*.*' -mtime +1
■ Execution result
./03-20200926145041-02.jpg
./03-20200926145042-00.jpg
./03-20200926145042-01.jpg
./03-20200926145042-02.jpg
./03-20200926145043-00.jpg
./03-20200926145043-01.jpg
./04-20200927183825.avi
./04-20200927183825-00.jpg
./04-20200927183825-01.jpg
./04-20200927183825-02.jpg
./04-20200927183826-00.jpg
./04-20200927183826-01.jpg
./04-20200927183826-02.jpg
./04-20200927183826-03.jpg
If you add the argument "-delete" to the above command, it will be deleted. Let's check with the following command.
■ Command
find /var/lib/motion -name '*.*' -mtime +1 -delete
■ Execution result The following error is displayed. The reason is that you do not have permission to delete the directory. In this case, use the "sudo" command with "root" privileges to delete the file.
find: cannot delete � /var/lib/motion/17-20200927213443-01.jpg. ‥: Permission denied
■ Delete again using the sudo command Execute the following command.
pi@raspberrypi:/var/lib/motion $ sudo find /var/lib/motion -name '*.*' -mtime +1 -delete
pi@raspberrypi:/var/lib/motion $
■ Check if deleted Confirm that the file is deleted and not displayed in the command execution result below.
pi@raspberrypi:/var/lib/motion $ sudo find /var/lib/motion -name '*.*' -mtime +1
pi@raspberrypi:/var/lib/motion $
On Linux, use cron to execute certain commands or programs on a regular basis. For Windows, it's the same as Task Scheduler.
■ Command It will be displayed the first time you execute it as shown in the screen below. I like the VI editor, so I choose 2.
pi@raspberrypi:/var/lib/motion $ crontab -e
no crontab for pi - using an empty one
Select an editor. To change later, run 'select-editor'.
1. /bin/nano <---- easiest
2. /usr/bin/vim.tiny
3. /bin/ed
Choose 1-3 [1]:2
■ cron settings Add the following line. Every day at 1:00, the command to delete files that are older than 31 days is executed.
Reference: cron configuration guide https://www.express.nec.co.jp/linux/distributions/knowledge/system/crond.html
m h dom mon dow command
0 1 * * * sudo find /var/lib/motion -name '*.*' -mtime +31 -delete
If you apply this content this time, you can compress the file, attach it to an email, and automatically upload it to Slack chat. I'll write a program to attach to emails and Slack in the near future.
Recommended Posts