Chris
Chris

Reputation: 12078

modify shell script to delete folders as well as files

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 ?

Upvotes: 1

Views: 1426

Answers (2)

codaddict
codaddict

Reputation: 455142

  • 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.

Upvotes: 2

user285879
user285879

Reputation:

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

Upvotes: 1

Related Questions