I have a task that requires me to delete all folders in a directory that aren’t symlinked, keeping only the symlinked folders and the symlinks.
If I have for instance 3 resources: link, linked_folder and unlinked folder. link and linked_folder will be kept.
Currently I have managed to get this code, which works for the file naming structure we have, but I’d like to know if there is a cleaner solution?
protected_folders=`ls -l | awk '/^l/ {printf $10}' | tr '/' '|'`;
symlinks=`ls -l | awk '/^l/ {print $8}' | tr "\n" "|"`;
protected_resources=$protected_folders$symlinks;
protected_resources=${protected_resources:0:${#protected_resources}-1};
folders_to_delete=`ls | grep -v -E "$protected_resources"`;
echo $folders_to_delete | tr '\n' ' ' | tr ' ' '\000' | xargs -0 rm -rf
I know the above command can be done on one line, but I’ve separated it as I’ve been requested to have it more “readable”.
Any help would be appreciated.
It might be easier to move the symlinks and their targets to a new directory, then replace the old directory with the new.
WARNING: this is just a rough sketch, to give you the idea. [UPDATE: clean up and make it less like pseudo-code]