【问题标题】:modify shell script to delete folders as well as files修改 shell 脚本以删除文件夹和文件
【发布时间】:2010-09-01 13:03:04
【问题描述】:

我的shell脚本:

#!/bin/bash
if [ $# -lt 2 ]
then
    echo "$0 : Not enough argument supplied. 2 Arguments needed."
    echo "Argument 1: -d for debug (lists files it will remove) or -e for execution."
    echo "Followed by some path to remove files from. (path of where to look) "
    exit 1
fi

if test $1 == '-d'
then
    find $2 -mmin +60 -type f -exec ls -l {} \;
elif test $1 == '-e'
then
    find $2 -mmin +60 -type f -exec rm -rf {} \;
fi

基本上,这将在作为第二个参数提供的给定目录中查找文件,并列出(-d 表示参数 1)或删除(-e 表示参数 1)>60 分钟前修改的文件。

我怎样才能修改它以删除文件夹?

【问题讨论】:

    标签: bash shell find rm


    【解决方案1】:
    • 删除-type f
    • ls -l 更改为ls -ld

    Change 1 将列出所有内容,而不仅仅是文件。这也包括链接。如果您不适合列出/删除文件和目录以外的任何内容,则需要分别列出/删除文件和目录:

    if test $1 == '-d'
    then
        find $2 -mmin +60 -type f -exec ls -ld {} \;
        find $2 -mmin +60 -type d -exec ls -ld {} \;
    elif test $1 == '-e'
    then
        find $2 -mmin +60 -type f -exec rm -rf {} \;
        find $2 -mmin +60 -type d -exec rm -rf {} \;
    fi
    

    需要更改 2,因为目录上的ls -l 将列出目录中的文件。

    【讨论】:

    • 可以结合-types:find $2 -mmin +60 \( -type f -o -type d \) -exec ls -ld {} \;
    • 警告:这可能不是你想要的:目录(包括 $2 本身)将被删除,即使它们中有活动文件/子目录,如果目录本身在过去一小时内没有被修改.避免这个问题……更复杂,尤其是在试运行模式下。
    【解决方案2】:
    #!/bin/bash
    if [ $# -lt 2 ]
    then
        echo "$0 : Not enough argument supplied. 2 Arguments needed."
        echo "Argument 1: -d for debug (lists files it will remove) or -e for execution."
        echo "Followed by some path to remove files from. (path of where to look) "
        exit 1
    fi
    
    if test $1 == '-d'
    then
        find $2 -mmin +60 -type d -exec ls -l {} \;
        find $2 -mmin +60 -type f -exec ls -l {} \;
    elif test $1 == '-e'
    then
        find $2 -mmin +60 -type d -exec rm -rf {} \;
        find $2 -mmin +60 -type f -exec rm -rf {} \;
    fi
    

    这应该适合你。

    【讨论】: