Reputation: 15066
I want to delete some revisions of docker images. I want to delete the last 2 lines. I'm able to print the last 2 lines with:
ls -lt | tail -n 2
gives my the 2 last lines.
drwxr-xr-x 2 root root 4096 Nov 9 10:56 541a303d3c82785293f89a401038ac33ef2b54b6aeb09efd3d3bda7xxxx
drwxr-xr-x 2 root root 4096 Oct 25 12:07 c74e1399c99de0c23517abc95bc9b16d09df5c4d518776e77d9ae67xxxx
Now is my question. How do I have to delete them?
I tried ls -lt | tail -n 2 | rm -r *
but than I deleted everything (the whole output of ls
)
Upvotes: 1
Views: 2910
Reputation: 884
You could get that to work. I would probably use something like rm -rf $(ls -t | tail -n2)
, but parsing ls
is really not recommended.
A cleaner way to do this would be to use find
. You can use that to delete everything before a certain time. Something like this: find . -mtime -180 -exec rm -f {} \;
would delete everything newer than 180 days ago.
I would highly recommend testing whatever you are planning to run before you actually do the delete!
Upvotes: 2
Reputation: 1619
Just for test :
ls -t | tail -n 2 | xargs -i -t echo {}
-t, --verbose Print the command line on the standard error output before executing it.
After the test, you can delete them with :
ls -t | tail -n 2 | xargs -i -t rm -fr {}
rm -fr 541a303d3c82785293f89a401038ac33ef2b54b6aeb09efd3d3bda7xxxx
rm -fr c74e1399c99de0c23517abc95bc9b16d09df5c4d518776e77d9ae67xxxx
Upvotes: 0
Reputation: 96
You have the right idea; however, whatever comes after 'rm' gets deleted, which is why * deleted all instead of what you were trying to pipe into it.
This is a pretty clean way to do it though
rm `ls | tail -n 2`
Upvotes: 1