简体   繁体   中英

Delete directories with xargs

I've got a list of folders I want to remove using xargs generated using find

find command

$ find /home/users/lukes -maxdepth 1 -type d > test.txt

test.txt

/home/users/lukes/2
/home/users/lukes/6
/home/users/lukes/7
/home/users/lukes/3
/home/users/lukes/1
/home/users/lukes/4
/home/users/lukes/5

command and --verbose output

$ xargs --verbose -0 -I{} rm -rfv {} < test.txt 
rm -rfv /home/users/lukes/2
/home/users/lukes/6
/home/users/lukes/7
/home/users/lukes/jadu_package_1.1.0
/home/users/lukes/3
/home/users/lukes/1
/home/users/lukes/4
/home/users/lukes/5

But the directories don't get removed ?

I'm using -0 as there could be whitespace when I run this for real, I'm generating the list so I can confirm every line is safe to be deleted in the text file rather than piping find directly to xargs

Any suggestions ?

So, let me start by saying I have a supreme dislike of xargs. It can be really dangerous if you are not careful. That being said, something like this would work:

find /home/users/luke -mindepth 1 -maxdepth 1 -type d|xargs --verbose -I{} rm -vfr "{}"

By throwing {} in double quotes, you remove any issues involving spaces. I tend to use "" or '' around stuff like that as often as possible. I put mindepth on there to ensure it does not include the parent folder, as some OS's have maxdepth include the parent directory (ie '.') which would effectively nuke the entire folder. I assume you don't want that.

Again, be VERY careful with xargs. That command can be evil. I would say add -0 on it first to have it show what will be run, then remove -0 once you are really sure.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM