Bash command not working - why?

Associate
Joined
8 May 2009
Posts
295
I've set up a cronjob to execute a backup script every 24 hours. It works almost perfectly except for this:


Code:
## SET THE BACK UP ROOT DIRECTORY ##                                                                                                                                                                                                                                                                                                                                                  
BACKUP_DIR=/home/backup                                                                                                  
                                                                                                                  
                                                                                                        
## CLEAN UP THE OLDER FILES - REMOVE OLDER FILES ##                                                                                                                                  
rm `find $BACKUP_DIR/HOME/* -type f -mtime +3`


The issue I've identified is that the backup files are named with spaces in the file name... I know I could just change the output so they don't have spaces, but I'm curious to solve it anyway just for experience.

As an example, out put files are:

home-backup-22 October 2016
home-backup-23 October 2016
home-backup-24 October 2016
home-backup-25 October 2016
home-backup-26 October 2016

...

So the command fails saying something like No such file: home-backup-22... obviously missing off the month/year due to the space.

Any ideas on how to tell it to do the whole file name including spaces?

Thanks
 
Soldato
Joined
18 Oct 2002
Posts
18,290
Location
Brighton
You could surround the command in double quotes:

Code:
rm "`find $BACKUP_DIR/HOME/* -type f -mtime +3`"

This will fail if you have more than one file and it's probably not what you should be doing.

You can just drop the rm altogether and let find handle the removal:

Code:
find $BACKUP_DIR/HOME/* -type f -mtime +3 -exec rm {} \;

n.b. You should get in to the habit of not putting spaces in filenames, you're just making life hard for yourself.
 
Associate
Joined
20 Jan 2013
Posts
134
I think you're also missing the -f from the rm command as well otherwise it would prompt for a 'y'.
 
Soldato
Joined
10 Oct 2005
Posts
8,705
Location
Nottingham
I think you're also missing the -f from the rm command as well otherwise it would prompt for a 'y'.

Or if you are seeing that then call rm by absolute path, usually /bin/rm, rather than just as rm, as the prompt is normally due to some distributions actually aliasing rm to rm -i in the shell.
 
Top Bottom