I have a series of boxes (over 1,000), that have the same directory that has been used over time as a dumping ground for various ‘stuff’, and now I need to have them cleaned up, save one sub-directory. What I need to know, is there a way to create a script that will allow any user to delete everything (hidden, directories, links, etc.) from a particular directory, except one sub-directory.
This is actually reasonably straightforward if you remember that anywhere you can use a shell expansion variable you can also invoke a script, simple or complex. So, if we were to tackle this basic Unix/Linux scripting task without any special requirements, we’d do this:
Or, a safer way to do this might be to use:
this would ultimately do the same thing, of course.
To omit one directory while removing everything else, however, the basic logic is to list all the files and directories in the specified common parent directory, but “screen out” the one we’d like to preserve. This can be done with:
(well, if you have files or directories with spaces in their names you have a little bit more work you’d need to do, but remember that sed or tr can temporarily change spaces to another character, let you filter out the directory to save, then change things back)
Using the preferred shell notation of $( ) for subshell commands (rather than the more traditional backticks), we’re now looking at a base command of:
See where I’m heading with this?
Now let’s make it a bit more flexible by dropping it into a for loop:
for dirname in $(ls * | sed ‘s/ /—/g’ | grep -v “$savedir”)
remove=$(echo $dirname | sed ‘s/—/ /g’)
echo “removing file or directory $remove”
rm -rf “$remove”
Now you can see where I’m going with all of this.
The other half of this challenge is to distribute the script onto the many, many boxes you have, and for that I’m wondering if you have a list of every system hostname / IP address? If so, you could create a temporary mount point directory on the master system, then iteratively mount – process – unmount each system until you’d gone through them all. Something vaguely like this:
for name in $(cat $systemnamelist)
echo “Attempting to mount $name”
mount $name $mountpoint
echo ” .. processing directory”
code goes here to clean out directory
echo ” .. done”
That might not be exactly what you need, but it should certainly help you get going in the right direction.