SSH command for looping through directories EXCEPT a few specified
Would it be possible to execute a bash command via SSH which loops over multiple directories EXCEPT 3 or 4 that I specify? Something like:
Delete public_html/outdated/
for all directories in /home/
except /home/exception1/
, /home/exce开发者_C百科ption2/
and /home/exception3/
I am on a HostGator Dedicated Linux server.
This is all one line, but I've split it here for readability
find /home
\( -wholename '/home/exception1'
-o -wholename '/home/exception2'
-o -wholename '/home/exception3' \)
-prune -o
-wholename '*/public_html/outdated' -type d
-exec rm -rvf \{} \;
Before running this I strongly suggest replacing the -exec rm -rvf \{} \;
bit with -print
to verify that it prints only what you want deleted.
Here's how it works: find
recursively finds stuff. the stuff in \(
...\)' matches directories you want to skip entirely (ie: prune). The standard pattern for using
-pruneis to say what you want to prune out, then
-prune -o`, and then the stuff you actually want to match.
We want to match public_html/outdated
directories, so that's what -wholename '*/public_html/outdated' -type d
is for. (-type d
means "is a directory").
Finally comes the action we want to perform. Once again, replace this part with -print
until you're sure it does what you want.
One caveat: This will spit out a bunch of warnings of the form:
find: `/home/foo/public_html/outdated': No such file or directory
This is because find is trying to walk into those directories it just deleted. You can safely ignore these -- find will continue despite the warnings.
Test first!
shopt -s extglob
rm -rf /home/!(exception1|exception2|exception3)/public_html/outdated/
Here's a simple solution - there's probably better ways to do this.
cd /home
ls */public_html/outdated
will should you all of those; you can use grep -v to remove lines from that
ls */public_html/outdated | grep -Ev ^exception1/ | grep -Ev ^exception2/ | grep -Ev ^exception3/
and then use backticks to feed these into rm -rf
rm -rf `ls */public_html/outdated | grep -Ev ^exception1/ | grep -Ev ^exception2/ | grep -Ev ^exception3/`
Obviously you should run the middle step to verify the list before you actually delete them!
Note that this may not work if any of your directories have spaces in - although usernames in /home shouldn't. The safe way to do that is using find
. (There's probably a way to do the exclusion with find but I can never remember.)
精彩评论