Method 1 – First moving, then deleting
Just move the files up one directory and then delete it. This will keep the contained file/folder hierarchy.
mv ~/Desktop/MyFolder/* ~/Desktop/MyFolder/..
rmdir ~/Desktop/MyFolder
Method 2 – Automating in a Shell Function
You can put this into a shell function defined in your ~/.bash_profile:
function rmd () {
if [ -d "$1" ]; then
mv "$1"/* "$1"/..
rmdir "$1"
else
echo "$1 is not a directory"
fi
}
As said before, this will only delete the parent folder, keeping the children hierarchy intact.
Method 3 – Recursive deletion
If you want to recursively remove all folders and just keep files contained, use the following instead:
function rmdr () {
if [ -d "$1" ]; then
p="$1"/..
find "$1" -type f -exec mv '{}' "$p" \;
rm -rf "$1"
else
echo "$1 is not a directory"
fi
}
Note that this overwrites files with duplicate names.
Method 4 – Recursive deletion with duplicate awareness
Finally, if you want to keep duplicate files, you can check if they already exist. In this case, we'll prepend them with a random number string. Of course, there could be way more sophisticated methods than that, but you can see where this is going.
function rmdr () {
if [ -d "$1" ]; then
p="$1"/..
# loop through all files
while IFS= read -r -d '' file; do
filename=$(basename "$file")
# if it already exists, prefix with random number
if [ -f "$p/$filename" ]; then
mv "$file" "$p/$RANDOM-$filename"
# if it doesn't exist, just move
else
mv "$file" "$p"
fi
done < <(find "$1" -type f -print0)
# remove parent directory
rm -rf "$1"
else
echo "$1 is not a directory"
fi
}
Looping through find output is explained here.
Where should the files go? – slhck – 2012-04-03T07:23:48.263
@slhck up a directory – gadgetmo – 2012-04-03T07:30:29.303