I am working on a linux script in which i have to delete the directories which are created before 7days. I have found a command which does the same. Below is the command
find /some/thing/ -type d -mtime +7 -exec rm -rf {} ;
But when i am checking the exit status of the command using echo $?
it is returning 1 even after deleting the files from the location.
To create a directory with old time stamp i am using the below set of commands. Creates a folder and then modified date to 2018-05-10
mkdir sample touch -t 1805100000.00 sample
Advertisement
Answer
The man find says
find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find.
That means if at least one directory was not possible to delete then the find returns something else than 1. If there is a directory structure like
/some/thing/subdir /some/thing/subdir/subsubdir
and both subsdirs are eligible to delete then find may delete the /some/thing/subdir
first and then delete of the /some/thing/subdir/subsubdir
fails because it does not exist anymore.
EDIT
The original answer contains explanation why but does not contain a proposal how to solve it. Deleep’s comment proposed to use the -depth
parameter to force find process each directory’s contents before the directory itself. Indeed it works:
find /some/thing/ -type d -mtime +7 -depth -exec rm -rf {} ;