I am trying to delete the oldest file in a tree with a script in Debian.
find /home/backups -type f \( -name \*.tgz -o -name \*.gz \) -print0 | xargs -0 ls -t | tail -1 | xargs -0 rm
But I am getting an error:
rm: cannot remove `/home/backups/tree/structure/file.2011-12-08_03-01-01.sql.gz\n': No such file or directory
Any ideas what I am doing wrong (or is there an easier/better way?), I have tried to RTFM, but am lost.
The
lsappends a newline and the last xargs -0 says the newline is part of the file name.Run the last xargs with
-d '\n'instead of-0.BTW, due to the way xargs works, your whole pipe is a bug waiting to happen. Consider a really long file name list produced by the
find, so that thexargs -0 lsrunslsmultiple times with subsets of the filenames. Only the oldest of the lastlsinvocation will make it past thetail -1. If the oldest file is actually, say, the very first filename output byfind, you are deleting a younger file.