R
R
Rollex2021-05-06 05:43:46
bash
Rollex, 2021-05-06 05:43:46

How to delete all but one file in a folder (bash)?

I collect database backups every 15 minutes and put them in folders by day (folder name example: 2021-05-05).
After a month, I want to pass the script through the folders and delete all files except one.
Can you tell me how to implement something like this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tema Smirnov, 2021-05-06
@TemaSM

#!/bin/bash

set -e
export LC_ALL=C
export TZ=Europe/Moscow

# папка с бэкапами
backups_dir="/backups"
# количество дней с момента создания файла/папки, после которого удалять бэкапы
backups_expire_days=30
# название файла (можно использовать маски), который нужно исключить из процесса удаления
filename_to_exclude="myfile.bin"

find "${backups_dir}/"* -ctime "+${backups_expire_days}" \( ! -name "${filename_to_exclude}" \) -exec rm -rf {} \;
# можно подставлять сразу несколько название файлов, пример:
# \( ! -name "myfile.bin" ! -name "*.log" \)

! This script executes rm -rf, which is dangerous. Therefore, double-check several times before executing in a particular folder.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question