Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

自動清除日期目錄的 Shell 腳本

很多時候備份會用到以日期建立的資料夾,而這些日期資料夾下又有許多子資料夾。若要整批移除這些日期目錄,單靠 find 搭配 rm 或 delete 顯得力不從心。本文提供一個簡單的小腳本,可嵌入其他腳本,也可直接調用,供各位參考。

1、腳本內容

[root@SZDB ~]# more purge_datedir.sh
#!/bin/bash
# Author: Leshami
# Blog  : https://www.linuxidc.com

RemoveDir=/log/hotbak/physical
dt=`date +%Y%m%d -d "3 day ago"`

for subdir in `ls $RemoveDir`;
do
    if [ "${subdir}" \< "${dt}" ];
        then
        rm -rf $RemoveDir/$subdir >/dev/null
        echo "The directory $RemoveDir/$subdir has been removed."
    fi
done

2、演示

執行前目錄中有多個日期資料夾:

[root@SZDB ~]# ls /log/hotbak/physical
20141203  20141210  20141217  20141224  20141231  20150107  20150114  20150125  tmp.sh
20141207  20141214  20141221  20141228  20150104  20150111  20150121  20150128

執行腳本後,三天前的日期目錄會被逐一移除:

[root@SZDB ~]# ./purge_datedir.sh
The directory /log/hotbak/physical/20141203 has been removed.
The directory /log/hotbak/physical/20141207 has been removed.
...

執行後僅保留較新的日期目錄:

[root@SZDB ~]# ls /log/hotbak/physical
20150125  20150128

延伸閱讀:

cat 指令利用 Linux 重定向合併檔案 https://www.linuxidc.com/Linux/2015-01/112122.htm

Shell 編程淺析 https://www.linuxidc.com/Linux/2014-08/105379.htm

Linux Shell 參數替換 https://www.linuxidc.com/Linux/2013-06/85356.htm

Linux Shell 通配符、轉義字元、元字元、特殊字元 https://www.linuxidc.com/Linux/2014-10/108111.htm

Copyright © Linux教程網 All Rights Reserved