Answer the question
In order to leave comments, you need to log in
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
#!/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" \)
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 questionAsk a Question
731 491 924 answers to any question