bash - Find a directory only contained within a certain folder
2014-07
I have a directory structure like:
foo
|__bar
|__bin
| |__tmp
|
|__bez
|__tmp
I need to find the tmp directory in bin/tmp, but not the one in bez/tmp. It seems to me that find only operates on the name of one directory or file at a time. Is there a command that will return me the path to the tmp directory in bin, but not the one in bez? It's a bonus if the command finds all bin/tmp folders, as there may be many in the directory tree.
Many thanks!
find ./foo/ -type d -path '*/bin/tmp'
I hacked together this script to rsync
some files over ssh
. The --remove-source-files
option of rsync
seems to remove the files it transfers, which is what I want. However, I also want the directories those files are placed in to be gone as well.
The current part of the find
command, -exec rmdir -p {} ;
tries to remove the parent directory (in this case, /srv/torrents
), but fails because it doesn't have the right permissions. What I'd like to do is stop rmdir
from traversing above the directory find
is run in, or find another solution to get rid of all the empty folders. I've thought of using some kind of loop with find
and running rmdir
without the -p
switch, but I thought it wouldn't work out.
Essentially, is there an alternative way to remove all the empty directories under the parent directory? Thanks in advance!
#!/bin/bash
HOST='<hostname>'
USER='<username>'
DIR='<destination directory>'
SOURCE='/srv/torrents/'
rsync -e "ssh -l $USER" --remove-source-files -h -4 -r --stats -m --progress -i $SOURCE $HOST:$DIR
find $SOURCE -mindepth 1 -type d -empty -prune -exec rmdir -p \{\} \;
You can make use of the fact that rmdir
won't remove a non-empty directory:
rmdir {,.}?*/ 2>/dev/null
or, if your version of rmdir
has the option:
rmdir --ignore-fail-on-non-empty {,.}?*/
The weird looking glob expands to include regular directories and hidden directories, but exclude .
and ..
.
You don't have to use find
unless you need to get at directories below the current level.
Edit:
Try:
find -type d -empty -delete
That does a depth-first search and deletes all empty nested directories.
you can also do
find $SOURCE -mindepth 1 -type d -empty -prune -print0 | xargs -0 rm -rf