我正在使用centOS8,并且正在撰寫一個批處理腳本來洗掉前一天的資料。
需要洗掉的檔案夾結構如下。
root/data/year/month/day/uuid/time
例如:
root
└ data
└ ImportantFolder
└ 2020
└ 2021
└ 11
└ 12
└ 1
└ 2
└ 550e8400-e29b-41d4-a716-446655440000
└ 2243010332.d
該腳本每天凌晨 2:00 運行,并且應該只洗掉前一天的資料。
例如,如果今天是 2022 年 1 月 1 日,則應洗掉截至 2021 年 12 月 31 日的檔案夾。
只洗掉資料檔案夾中超過一天前創建的檔案會很簡單,但不應洗掉資料檔案夾中不遵循年/月/日/..結構的資料(如上面的重要檔案夾),并且只應保留午夜之后創建的檔案夾。(系統 24/7 作業)
所以,腳本執行的時候,我在想是否可以得到昨天的日期,分解日月年,然后通過條件陳述句洗掉。我是 shellscript 的新手,所以我不知道這是否可能。你能幫我一個更好的主意,或者我如何用一個腳本來獲取和反匯編前一天的內容嗎?
我通過參考答案中的指南撰寫的腳本如下。這是一個初學者的腳本,但我希望它可以幫助某人。
#!/bin/bash
function rm_Ymd_forder(){
current_year=$(($(date %Y)))
current_month=$(($(date %m)))
current_day=$(($(date %d)))
base_dir=/data
for current_dir in "$base_dir"/*/; do
current_dir=$(basename "$current_dir")
if [ "$current_dir" -lt "$current_year" ];
then
rm -rf "$base_dir"/"$current_dir"
echo "$base_dir"/"$current_dir" "Deleted"
fi;
done
for current_dir2 in "$base_dir"/"$current_year"/*/; do
current_dir2=$(basename "$current_dir2")
if [ "$current_dir2" -lt "$current_month" ];
then
rm -rf "$base_dir"/"$current_year"/"$current_dir2"
echo "$base_dir"/"$current_year"/"$currnet_dir2" "Deleted"
fi;
done
for current_dir3 in "$base_dir"/"$current_year"/"$current_month"/*/; do
current_dir3=$(basename "$current_dir3")
if [ "$current_dir3" -lt "$current_day" ];
then
rm -rf "$base_dir"/"$current_year"/"$current_month"/"$current_dir3"
echo "$base_dir"/"$current_year"/"$current_month"/"$current_dir3" "Deleted"
fi;
done
}
(
set -e
rm_Ymd_forder
)
errorCode=$?
if [ $errorCode -ne 0 ]; then
echo "Error"
exit $errorCode
else
echo "OK"
exit 0
fi
uj5u.com熱心網友回復:
以下是一些指導方針:
- 使用GNU date獲取各種日期段
- 示例:
current_year=$(date %Y)將為您提供當前年份
- 示例:
- 使用這種型別的代碼回圈遍歷目錄,一次一層
- 示例:
for current_dir in /data/*/; do...
- 示例:
- 使用基本名稱或字串修改僅獲取每個專案的目錄名稱(去掉斜杠)
- 例子:
current_dir=$(basename "$current_dir")
- 例子:
- 在每個級別,檢查數字是否低于當前年/月/日(取決于級別)
- 使用 -lt / -gt 進行比較
- 示例:
if [ "$current_dir" -lt "$current_year" ]; then...(洗掉它 - 或做一些日志記錄以確保您在軌道上)
- 如果數字等于(-eq)當前年/月 - 那么你可以回圈通過下一個
- 示例:
for current_dir2 in /data/"$current_dir"/*/; do...
- 示例:
uj5u.com熱心網友回復:
你可以嘗試這樣的事情:
find /root/data -type d -not -name "ImportantFolder" -mtime 1 -exec rm -rf {} \;
因此,僅搜索目錄,不包括“ImportantFolder”(未測驗)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417464.html
標籤:
