从闪存驱动器中删除所有存档

时间:2014-06-10 14:17:50

标签: arrays bash flash archive

编写了一个BASH脚本来查找/删除插入的闪存驱动器中的所有存档。

需要我的代码反馈。希望它写得正确:

#! /bin/bash
# Author:       Nyle Davis          Created 14-06-12
# Purpose:      Empty the inserted flash of any/all .tar type backup files.
# File:         clean-drives.sh

function findtar {
    BDRV=$1;                                                        # If target dir not passed then
    if [ -z ${BDRV} ]; then                             # hardcode to last known good
        BDRV="/mnt/flash/64Gig";                        # mount point.
    fi
    CWD=$(pwd);
    cd ${BDRV};
    # Capture in array all compression file extensions
    compray=(a, afa, apk, ar, ark, bz2, bzip2, cfs, dar, gz, gzip, iso, jar. kgb, 
                lz, lzma, lzo, rz, mar, pak6, pak7, pak8, par, par2, pea, rar, rk, 
                shar, tar, tbz2, tgz, tlz, xz, yzl, z, zip, zipx, zoo, zpak, zz, 7z);
    for i in ${compray[@]}; do
        for n in $(find . -name "*.${i}" ) ; do #find & delete archive files
            rm -f ${n};
        done;       # end: for n in $find 
    done;           # end: for i in $compray
    cd ${CWD};
}

findtar;

exit 0;

1 个答案:

答案 0 :(得分:0)

您的代码可以简化为:

function findtar {
    local BDRV=${1:-"/mnt/flash/64Gig"} IFS='|'
    local compray=(a afa apk ar ark bz2 bzip2 cfs dar gz gzip iso jar kgb 
                lz lzma lzo rz mar pak6 pak7 pak8 par par2 pea rar rk 
                shar tar tbz2 tgz tlz xz yzl z zip zipx zoo zpak zz 7z)

    find "$BDRV" -regextype posix-egrep -regex ".*[.](${compray[*]})$" ## -delete
}

findtar

我评论了-delete。如果您要删除文件,只需添加即可。在你做之前先测试代码。

其他形式:

find "$BDRV" -regextype posix-egrep -regex ".*[.](${compray[*]})$" -print0 | xargs -0 rm -f --

find "$BDRV" -regextype posix-egrep -regex ".*[.](${compray[*]})$" -print0 | while IFS= read -r -d $'\0'; do
    rm -f -- "$REPLY"
done

while IFS= read -r -d $'\0'; do
    rm -f -- "$REPLY"
done < <(exec find "$BDRV" -regextype posix-egrep -regex ".*[.](${compray[*]})$" -print0)

readarray -t FILES < <(exec find "$BDRV" -regextype posix-egrep -regex ".*[.](${compray[*]})$)" && \
    rm -f -- "${FILES[@]}"