Page 1 of 1

How to remove multiple folders with rm command? (Solved)

Posted: Tue Jan 16, 2024 7:15 am
by amethyst

I'm looking at this piece of code for extracting a package:

Code: Select all

extract_pkg() {
	PKG=$1
	cd /
	for x in `cat $D/$PKG`; do [ -d $x ] && MYPATH="$x" || cp --parents -a "${MYPATH}/$x" $WrkDir; done
			 
}

Instead I want to remove the package so I changed that last line to:

Code: Select all

for x in `cat $D/$PKG`; do [ -d $x ] && MYPATH="$x" || rm -r "${MYPATH}/$x"; done

This deletes the files in the top folders and subfolders but now I sit with empty top folders and subfolders that also need to be removed (those applicable to the specific package of course). So how do I do it, adding the -d option does not work.


Re: Need assistance with rm command for multiple folders

Posted: Tue Jan 16, 2024 12:13 pm
by Trapster

rmdir ?


Re: Need assistance with rm command for multiple folders

Posted: Tue Jan 16, 2024 1:01 pm
by amethyst
Trapster wrote: Tue Jan 16, 2024 12:13 pm

rmdir ?

How would I add it to that line so that it is done after the rm command (obviously targeting the correct empty directories)?


Re: Need assistance with rm command for multiple folders

Posted: Tue Jan 16, 2024 2:06 pm
by Trapster

I'd be more curious on why rm -r is not removing the directories


Re: How to remove multiple folders with rm command?

Posted: Tue Jan 16, 2024 2:15 pm
by Flash

Doesn't the rmdir command remove a directory and its contents?


Re: How to remove multiple folders with rm command?

Posted: Tue Jan 16, 2024 2:23 pm
by Trapster
Flash wrote: Tue Jan 16, 2024 2:15 pm

Doesn't the rmdir command remove a directory and its contents?

No, only empty directories.
rm -r should remove directories and contents recursively
rm -rf would force the removal but one needs to be careful with that.


Re: Need assistance with rm command for multiple folders

Posted: Tue Jan 16, 2024 3:07 pm
by amethyst
Trapster wrote: Tue Jan 16, 2024 2:06 pm

I'd be more curious on why rm -r is not removing the directories

I think I know what went wrong. Instead of targeting the top folders, the script targeted the full file paths. So the actual files were targeted and not the parent folders and its contents.


Re: How to remove multiple folders with rm command? (Closed)

Posted: Wed Jan 17, 2024 6:49 am
by amethyst

This is what happens when you forget about things you have done prior already. The application I was working on has already been published by me a long time ago. :oops: I see with that one that the code was slightly different but I did use rm followed by rmdir. Anyways, here is the application for those interested: viewtopic.php?p=90901#p90901