tags:

views:

47

answers:

2

My shell script:

#!/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

Basically this will find files in a given directory provided as second argument and either list (-d for argument 1) or remove (-e for argument 1) files modified >60 minutes ago.

How can I rework this to also remove folders ?

+2  A: 
  • Remove -type f
  • changing ls -l to ls -ld

Change 1 will list everything and not just files. This includes links as well. If you are not fine with listing/deleting anything other than files and directories then you need to separately list/delete files and directories as:

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

Change 2 is needed as ls -l on a directory will list the files in the directories.

codaddict
Oh geez, wow sorry for wasting your time. Thanks.
Chris
You can combine the `-types`: `find $2 -mmin +60 \( -type f -o -type d \) -exec ls -ld {} \;`
Dennis Williamson
Warning: this may not do what you want: directories (including $2 itself) will be deleted even if they have active files/subdirs in them, if the directory itself has not been modified in the last hour. Avoiding this problem is ... more complicated, especially in dry run mode.
Gordon Davisson
+1  A: 
#!/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

That should work for you.

Trevor Lalish-Menagh